C++ two stacks 0ms


  • 0
    S
    class Solution {
    public:
        string decodeString(string s) {
            int N = s.size(), i = 0, j = 0;
            stack<int> stki;
            string res = "";
            stack<string> stks;
            stks.push(res);
            while(i<N){
                if(isdigit(s[i])){
                    int n = 0;
                    while(i<N && isdigit(s[i]))  {
                        n = n*10 + s[i] - '0';
                        i++;
                    }
                    stki.push(n);
                }
                else if(s[i] == '['){
                    stks.push(res);
                    res.clear();
                    i++;
                }
                else if(s[i] == ']'){
                    string t = stks.top();
                    stks.pop();
                    int nRepeat = stki.top();
                    stki.pop();
                    for(int i=0;i<nRepeat;i++){
                        t += res;
                    }
                    res = t;
                    i++;
                }
                else{
                    res.push_back(s[i]);
                    i++;
                }
            }
            return res;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.