其他分享
首页 > 其他分享> > 394. 字符串解码 (括号 stack)

394. 字符串解码 (括号 stack)

作者:互联网

 

难度中等

给定一个经过编码的字符串,返回它解码后的字符串。

编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。

你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。

此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。

 

示例 1:

输入:s = "3[a]2[bc]"
输出:"aaabcbc"

示例 2:

输入:s = "3[a2[c]]"
输出:"accaccacc"

示例 3:

输入:s = "2[abc]3[cd]ef"
输出:"abcabccdcdcdef"

示例 4:

输入:s = "abc3[cd]xyz"
输出:"abccdcdcdxyz"


class Solution {
public:
    string decodeString(string s) {
        stack<int> q_cnt;
        stack<char> q_str;
        int i = 0;
        int k = 0;
        while(i < s.size()) {
            auto ch = s[i];
            if (0<= ch-'0' && ch -'0' <=9) {
                k = k*10 + ch -'0'; //
            } else if (ch == '[') {
                q_cnt.push(k);
                k = 0;
                q_str.push(ch);
            } else if (ch ==']') {
                vector<char> chars;
                while(!q_str.empty()) {
                    char top = q_str.top();
                    q_str.pop();
                    if (top == '[') {
                        break;
                    }
                    chars.emplace_back(top);
                }
                //cout << chars << endl;
                int cnt = q_cnt.top();q_cnt.pop();
                reverse(chars.begin(),chars.end());
                for(int kk = 0; kk < cnt; kk++) {
                    for(auto ch : chars) {
                        q_str.push(ch);
                    }
                }
            } else {
                q_str.push(ch);
            }
            i++;
        }
        vector<char> res;;
        while(!q_str.empty()) {
            auto ch = q_str.top();
            res.emplace_back(ch);
            //cout << ch << endl;
            q_str.pop();
        }
        reverse(res.begin(),res.end());
        string res_str = string(res.begin(),res.end());
        return res_str;
    }
};

 

标签:string,示例,解码,stack,str,394,字符串,top,输入
来源: https://www.cnblogs.com/zle1992/p/16526741.html