天天看点

leetcode菜狗入门 | 394. 字符串解码字符串解码

字符串解码

题目描述

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

编码规则为: 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".
           

解题思路

建两个栈,一个数字栈一个字符栈,数字栈存放倍数。字符栈如果遇到 ‘]’,就出栈直至遇到 ‘[’ ,数字栈栈顶出栈,把出栈的字符串按照倍数进行变换,如果字符栈非空就在放入字符栈,否则拼接在 ans 后,如果字符栈与数字栈全为空,就将当前字符直接拼在 ans后

代码

class Solution {
public:
    string decodeString(string s) {
        stack<int> count;
        stack<char> str;
        string ans = "";
        if(s.length() == 0) return ans;
        int i = 0;
        int num = -1;
        while(i < s.length()){
            while(s[i] >= '0' && s[i] <= '9' && i < s.length()){
                if(num == -1)
                    num = s[i] - '0';
                else
                    num = num*10 + (s[i]-'0');
                i++;
            }
            if(num != -1){
                count.push(num);
                num = -1;
            }
            if(count.empty() && str.empty()){
                ans.push_back(s[i]);
                i++;
                continue;
            }
            if(s[i] != ']'){
                str.push(s[i]);
                i++;
            }
            else{
                string temp = "";
                while(str.top() != '['){
                    temp.push_back(str.top());
                    str.pop();
                }
                str.pop();
                reverse(temp.begin(), temp.end());
                int beishu = count.top();
                //cout<<beishu<<endl;
                count.pop();
                string cur = temp;
                for(int j = 1; j <beishu; j++){
                    temp += cur;
                }
                if(str.empty())
                    ans += temp;
                else{
                    for(int j = 0; j < temp.length(); j++){
                        str.push(temp[j]);
                    }
                }
                i++;
            }
        }
        return ans;
    }
};