c++ 0ms solution using recursion


  • 0
    W
        string stringTimes(string &s, int times) {
            string res = s;
            int cnt = 1;
            while(cnt < times) {
                res += s;
                cnt++;
            }
            return res;
        }
        int getNumber(string &s, int &begin) {
            int num = 0;
            while(begin < s.length() && isdigit(s[begin])) {
                num = num * 10 + (s[begin]-'0');
                begin++;
            }
            begin--;
            return num;
        }
        string helper(string &s, int &begin) {
            string res = "";
            int times = 0;
            while(begin < s.length()) {
                char c = s[begin];
                if(c == '[') {
                    begin++;
                    string cur = helper(s, begin); //begin will be moved to matching ']'
                    res += stringTimes(cur, times);
                    times = 0;
                } else if(isdigit(c)) {
                    times = getNumber(s, begin);
                } else if(c == ']') {
                    return res;
                } else {
                    res += s[begin];
                }
                begin++;
            }
            return res;
        }
    public:
        string decodeString(string s) {
            int begin = 0;
            return helper(s, begin);
        }
    };
    

    I used a reference (begin) to denote the current progress.


Log in to reply
 

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