C++ recursive 0ms


  • 0
    class Solution {
    public:
        string helper(string s) {
            int pos = 0, num=0;
            string res,mid,after;
            
            while(!isdigit(s[pos])) pos++;
            res = s.substr(0,pos);
            
            if(pos<s.size()) {
                num = stoi(s.substr(pos));
                while(isdigit(s[pos])) pos++;
                stack<char> stk;
                stk.push('[');
                pos++;
                int spos = pos;
                while(!stk.empty()) {
                    if(s[pos]=='[') {
                        stk.push('[');
                    } else if(s[pos]==']') {
                        stk.pop();
                    }
                    pos++;
                }
                mid = helper(s.substr(spos,pos-spos-1));
                for(int i=0;i<num;i++) {
                    res+=mid;
                }
            }
            
            if(pos<s.size()) {
                after = helper(s.substr(pos));
                res += after;
            }
            
            return res;
        }
        string decodeString(string s) {
            if(s.empty()) return "";
            return helper(s);
        }
    };
    

Log in to reply
 

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