0394.cpp (776B)
1 class Solution { 2 public: 3 string decodeString(string s) { 4 stack<int> is; 5 stack<string> ss; 6 7 ss.push(""); 8 for (int i = 0; i < s.size(); i++) { 9 if (isdigit(s[i])) { 10 int res = 0; 11 do { 12 res *= 10; 13 res += s[i] - '0'; 14 } while (isdigit(s[++i])); 15 is.push(res); 16 ss.push(""); 17 } else if (s[i] == ']') { 18 string res = ""; 19 while (is.top()--) 20 res += ss.top(); 21 is.pop(); 22 ss.pop(); 23 ss.top() += res; 24 } else { 25 ss.top() += s[i]; 26 } 27 } 28 29 return ss.top(); 30 } 31 };