天天看点

LeetCode_394. Decode String 字符串解码

题目描述:

LeetCode_394. Decode String 字符串解码

思路:首先想到使用栈来存放数据,一个数字栈,一个字符栈。

1.当遇到数字的时候就统计数字(注意数字可能会超过一位数)

2.当遇到字符的时候就记录下来

class Solution {
public:
    string decodeString(string s) {
        int num=0;//用于统计数字结果
        for(char c:s){
            if(isdigit(c))
                num=num*10+(c-'0');
            else if(isalpha(c)){
                res+=c;
            }else if(c=='['){
                chars.push(res);
                nums.push(num);
                res="";
                num=0;
            }else{
                string temp=res;//已经重复一次了
                for(int i=0;i<nums.top()-1;i++)//在这里少重复一次
                    res+=temp;
                res=chars.top()+res;
                chars.pop();
                nums.pop();
            }
        }
        return res;
    }
private:
    stack<string> chars;
    stack<int> nums;
    string res;
};