LeetCode/LintCode

394. Decode String

2021-01-09  本文已影响0人  greatseniorsde

用两个stack,一个stack存repetition num(count), 一个stack存已经decode好的string. 几个keys:

class Solution {
public:
   
    stack<int> counts;
    stack<string> decodedStrings;
    int count = 0;
    string currentString;
    
    string decodeString(string s) {
        for (char ch : s){
            if (isdigit(ch)){
                count = count*10 + ch - '0';
            } else if (ch == '['){
                counts.push(count);
                count = 0;
                decodedStrings.push(currentString);
                currentString = "";
            } else if (ch == ']'){
                string decodedString = decodedStrings.top();
                decodedStrings.pop();
                for (int i = 0; i < counts.top(); i++){
                    decodedString += currentString;
                }
                counts.pop();               
                currentString = decodedString;
            } else {
                currentString += ch;
            }
        }
        return currentString;
    }
};


// Input: s = "3[a]2[bc]"
// Output: "aaabcbc"
    
    
// Input: s = "3[a2[c]]"
// Output: "accaccacc"   



Time complexity: O(max(count)*length(s))

Space complexity: O(m+n)
m: # of digits in s;
n: # of letters in s;

上一篇 下一篇

猜你喜欢

热点阅读