0ms, using stack, easy to understand!


  • 0
    X

    ···
    class Solution {
    public:
    string decodeString(string s) {

        stack<int> ss; //use stack to store the number of letters (variable name:cnt) and the number of repetition(variable name:rep) before each '['.
        string res;
        int cnt=0,rep=0;
        for(int i=0;i<s.size();i++){
            if(s[i]=='['){
                ss.push(cnt);
                cnt=0;
                ss.push(rep);
                rep=0;
            }else if(s[i]==']'){
                int sz=res.size();
                string tmp=res.substr(sz-cnt);
                
                int factor=ss.top();
                ss.pop();
                cnt=factor*cnt+ss.top();
                ss.pop();
                while(factor>1){
                    res+=tmp;
                    factor--;
                }
            }else if(s[i]-'a'>=0&&s[i]-'a'<=26){
                res+=s[i];
                cnt++;
            }else if(s[i]-'0'>=0&&s[i]-'0'<=9){
                rep=rep*10+s[i]-'0';
            }
        }
        return res;
    }
    

    };
    ···


Log in to reply
 

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