题解 | #字符串解码#

字符串解码

https://www.nowcoder.com/practice/4e008fd863bb4681b54fb438bb859b92

using System;
using System.Collections.Generic;
using System.Text;

class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @return string字符串
     */
    public string decodeString (string s) {
        // write code here
        // write code here
        if (string.IsNullOrWhiteSpace(s))
            return s;
        Stack<char> cStack = new Stack<char>();
        foreach (char c in s) {
            if (c == ']') {
                StringBuilder sb = new StringBuilder();
                while (cStack.Count != 0 && cStack.Peek() != '[')
                    sb.Insert(0, cStack.Pop());
                cStack.Pop();
                StringBuilder sbN = new StringBuilder();
                while (cStack.Count != 0 && cStack.Peek() >= '0' && cStack.Peek() <= '9')
                    sbN.Insert(0, cStack.Pop());
                //cStack.Pop();
                for (int n = 0; n < int.Parse(sbN.ToString()); n++) {
                    for (int i = 0; i < sb.Length; i++)
                        cStack.Push(sb[i]);
                }
            } else
                cStack.Push(c);
        }
        StringBuilder sbR = new StringBuilder();
        while (cStack.Count != 0)
            sbR.Insert(0, cStack.Pop());
        return sbR.ToString();
    }
}

全部评论

相关推荐

去B座二楼砸水泥地:不过也可以理解,这种应该没参加过秋招
点赞 评论 收藏
分享
勇敢的联想人前程似锦:如果我是你,身体素质好我会去参军,然后走士兵计划考研211只需要200多分。
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务