C++ 0ms recursive code


  • 0
    F
    class Solution {
    public:
        int decode(const string &s, size_t idx, string &outStr)
        {
            //s[idx] must be either the first char of the original string or the first char in a [..]
            //return the length of chars processed
            size_t iStart = idx;
            while(idx != s.size() && s[idx] != ']') { 
                if(!isdigit(s[idx])) {
                    outStr.push_back(s[idx]);
                    ++idx;
                }else{
                    int nRep = 0;
                    char *pStart = (char*)&s[idx];
                    char *pEnd = pStart;
                    nRep = strtol(pStart, &pEnd, 10);
                    string subStr;
                    idx = idx + (pEnd - pStart) + 1;    // consume '['
                    int numProcessed = decode(s, idx, subStr);
                    while(nRep > 0) {
                        outStr += subStr;
                        --nRep;
                    }
                    idx += numProcessed + 1;    // consume ']'
                }
            }
            return idx - iStart;
        }
    
        string decodeString(string s) {
            string outStr;
            int len = decode(s, 0, outStr);
            return outStr;
        }
    };

Log in to reply
 

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