# leetcode 394. Decode String

leetcode 394. Decode String

s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".


class Solution {
public:
string decodeString(string s) {
string ans = "";
int num = 0;
stack<int> s_num;
stack<string> s_str;
for (int i = 0; i<s.size(); i++)
{
if (s[i] >= '0' && s[i] <= '9')
num = num * 10 + s[i] - '0';
else if (s[i] == '[')
{
s_num.push(num);
s_str.push(ans);
num = 0;
ans.clear();
}
else if (s[i] == ']')
{
int k = s_num.top();
s_num.pop();
string temp = s_str.top();
for (int j = 0; j<k; j++)
s_str.top() += ans;
ans = s_str.top();
s_str.pop();
}
else
ans += s[i];
}
return s_str.empty() ? ans : s_str.top();
}

};

class Solution {
public:
string decodeString(string s) {
int i = 0;
return decode(s, i);
}
string decode(string s, int& i) {
string res = "";
int n = s.size();
while (i < n && s[i] != ']') {
if (s[i] < '0' || s[i] > '9') {
res += s[i++];
} else {
int cnt = 0;
while (i < n && s[i] >= '0' && s[i] <= '9') {
cnt = cnt * 10 + s[i++] - '0';
}
++i;
string t = decode(s, i);
++i;
while (cnt-- > 0) {
res += t;
}
}
}
return res;
}
};