C++ recursion solution


  • 0
    M

    It's very clear that when meets num[str] call decodeString(str) in recursion.

       string decodeString(string s) {
            string ret, cur;
            int k = 0;
            int pt = 0; // pathless num
            for (int i = 0; i < s.length(); i++) {
                if (s[i] <= '9' && s[i] >= '0' && pt == 0) { // first num K
                    k = k * 10 + s[i] - '0';
                } else {
                    // is sub string [ sub-string ], or pure characters "aaaa"
                    if (s[i] == '[') {
                        ++pt;
                        if (pt > 1) cur += s[i];
                    } else if (s[i] == ']') {
                        if (pt > 1) cur += s[i];
                        --pt;
                        if (pt == 0) {
                            cur = decodeString(cur);
                            for (int j = 0; j < k; j++) ret += cur;
                            k = 0;
                            cur = "";
                        }
                    } else {
                        if (pt == 0) ret += s[i];
                        if (pt > 0) cur += s[i];
                    }
                }
                
            }
            return ret;
        }
    
    

Log in to reply
 

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