题目
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像3a或2[4]的输入。
示例
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
题目分析
由于这道题可能会遇到括号嵌套的情况,所以需要用到辅助栈,我用了两个栈,分别储存字符和重复的次数(需要注意重复次数是可能大于10的)。
stack<char> s_char;
stack<itn> s_num;
遍历给定的字符串s:
- 如果是数字或字母,压入栈
s_char; - 如果是'[',说明上一组数字结束了,依次弹出栈,组成遍历次数,压入栈
s_num; - 如果是']',说明上一组字母结束了,依次将字母弹出栈,组成字符串
t,翻转t,然后根据数字辅助栈s_num栈顶的数值s_num.top(),复制t,弹出数字辅助栈栈顶元素。将复制后的t压入字母栈s_char中。 
遍历结束后,将s_char中元素转换为字符串,返回该字符串即可。
题目解答
class Solution {
public:
    string decodeString(string s) {
        if (s.length() == 0) return s;
        stack<char> s_char;
        stack<int> s_num;
        int num;
        for (auto temp : s) {
            // 数字和字母 入栈
            if (isdigit(temp) || isalpha(temp)) {
                s_char.push(temp);
            }else if (temp == '[') {
                // 数字结束了
                num = 0;
                int dig = 1;
                while ( !s_char.empty() && isdigit(s_char.top()) ) {
                    num += (s_char.top() - '0') * dig;
                    dig *= 10;
                    s_char.pop();
                }
                s_num.push(num);
                s_char.push(temp);
                // ']'
            }else if (temp == ']'){
                string t;
                while (s_char.top() != '[') {
                    t += s_char.top();
                    s_char.pop();
                }
                // 弹出'['
                s_char.pop();
                reverse(t.begin(), t.end());
                string c = t;
                num = s_num.top();
                s_num.pop();
                while (num > 1) {
                    t += c;
                    num--;
                }
                for (auto tt : t) {
                    s_char.push(tt);
                }
            }
        }
        string res;
        while (!s_char.empty()){
            res += s_char.top();
            s_char.pop();
        }
        reverse(res.begin(), res.end());
        return res;
    }
};