LeetCode Hot100 394.字符串解码

class Solution {    
public:
    string decodeString(string s) {
        //使用两个栈:栈 1 存储数字;栈 2 存储待拼接的string
        //在遇到']'时,两个栈栈顶出栈
        string number;
        string res;
        stack<int> numStack;
        stack<string> strStack;
        for(char c : s){
            if(isdigit(c)){
                number.push_back(c);
            }else if(c == '['){
                int num = stoi(number);
                numStack.push(num);
                strStack.push(res);
                number = "";
                res = "";
            }else if(c == ']'){
                int repeatTimes = numStack.top();
                numStack.pop();
                string temp;
                for(int i = 0; i < repeatTimes; i++){
                    temp += res;
                }
                res = strStack.top() + temp;
                strStack.pop();
            }else{
                res.push_back(c); 
            }
        }
        return res;
    }
};

你可能感兴趣的:(LeetCode每日刷题记录,#,LeetCode中等题,leetcode,算法)