| 1 | class Solution { |
| 2 | public: |
| 3 | string decodeString(string s) { |
| 4 | stack<string> chars; |
| 5 | stack<int> nums; |
| 6 | string res; |
| 7 | int num = 0; |
| 8 | for(char c : s) { |
| 9 | if(isdigit(c)) { |
| 10 | num = num*10 + (c-'0'); |
| 11 | } |
| 12 | else if(isalpha(c)) { |
| 13 | res.push_back(c); |
| 14 | } |
| 15 | else if(c == '[') { |
| 16 | chars.push(res); |
| 17 | nums.push(num); |
| 18 | res = ""; |
| 19 | num = 0; |
| 20 | } |
| 21 | else if(c == ']') { |
| 22 | string tmp = res; |
| 23 | for(int i = 0; i < nums.top()-1; ++i) { |
| 24 | res += tmp; |
| 25 | } |
| 26 | res = chars.top() + res; |
| 27 | chars.pop(); nums.pop(); |
| 28 | } |
| 29 | } |
| 30 | return res; |
| 31 | } |
| 32 | }; |