Concise C++ non-recursive solution


  • 0
    H

    Use the result string res as a stack. When ']' appears, get the repetition string and repeat times.

    class Solution {
    public:
        string decodeString(string s) {
            string res;
            for (auto c : s) {
                if (c != ']') {
                    res.push_back(c);
                    continue;
                }
                int i = res.find_last_of('[');
                int j = i;
                while (j > 0 && isdigit(res[j-1])) j--;
                string t = res.substr(i+1);
                int n = stoi(res.substr(j, i-j));
                res = res.substr(0, j);
                while(n-- > 0) res += t;
            }
            return res;
        }
    };
    

Log in to reply
 

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