Leetcode::Decode String

point

Design

Big O(time)

Code

class Solution {
public:

    // s[i]
    int getNum(string s, int & i) {
        int ret = 0;
        while(s[i] >= '0' && s[i] <= '9') {
            ret = ret * 10 + (s[i] - '0');
            i++;
        }
        return ret;
    }
    string getString(string s, int & i) {
        string str = "";
        while(s[i] >= 'a' && s[i] <= 'z') {
            str += s[i];
            i++;
        }
        return str;
    }
    string decodeString(string s) {
        vector<int> times;
        vector<string> strings;
        string ans = "";


        for(int i = 0; s[i]; i++) {
            if (s[i] >= '0' && s[i] <= '9') {
                int ti = getNum(s, i);
                // s[i+1] == '['
                if (s[i] != '[') static_assert("WRONG", "EXCEPTION");
                i += 1;
                string str = getString(s, i); i--;
                times.push_back(ti);
                strings.push_back(str);
            }
            else if (s[i] >= 'a' && s[i] <= 'z') {
                string str = getString(s, i); i--;
                if (strings.empty()) ans += str;
                else strings.back() = strings.back() + str;
            }
            else if (s[i] == ']') {
                if (times.empty() || strings.empty()) static_assert("WRONG", "EXCEPTION");
                string str = strings.back(); strings.pop_back();
                int ti = times.back();       times.pop_back();
                string totStr = "";
                while(ti--) totStr += str;

                if(strings.empty()) ans += totStr;
                else strings.back() = strings.back() + totStr;
            } else {
                static_assert("WRONG", "EXCEPTION");
            }
        }
        return ans;
    }
};