Decode String

给一个k[str]格式的string, 变成decode后k个str, 求decode后的string.

这题主要是case要想全, 并且str里面不会有数字, 这个很关键, 就是只要有数字就是k[str]格式, 那么就简单多了. 我看到有人用stack,我觉得没必要吧….

class Solution {
public:
    string decodeString(string s) {  
        int left = 0;
        while(left < s.length()) {
            if(isdigit(s[left])) {
                int n; // repeating times
                string n_str; // repeat string
                // start to find the n
                int right = left; 
                 while(isdigit(s[right])){
                    right++;
                }
                n = stoi(s.substr(left, right));
                // start to find the n_str
                int tail = right+1;
                int count = 1;
                while(count != 0) {
                    if(s[tail] == '[') {
                        count++;
                    }
                    if(s[tail] == ']') {
                        count--;
                    }
                    tail++;
                }
                int f = s.find('[');
                n_str = s.substr( f + 1, tail - f - 2);
                return decodeString(s.substr(0,left) + repeat(n_str, n) + s.substr(tail));
            }
            left++;
        } 
        return s;
    }
    
    string repeat(string s, int n) {
        string s1 = s;
        for(int i = 1; i < n; i++) {
            s1 += s;
        }
        return s1; 
    }
};