Problem :
Given an encoded string, return it’s decoded string.
The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer.
You may assume that the input string is always valid; No extra white spaces, square brackets are well-formed, etc.
Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, k. For example, there won’t be input like 3a or 2[4].
Example:
Examples:
s = "3[a]2[bc]", return "aaabcbc".
s = "3[a2[c]]", return "accaccacc".
s = "2[abc]3[cd]ef", return "abcabccdcdcdef".
**
Algorithm:
**
重点:用两个栈,一个存数字,一个存方括号里的字符串。
**
Code:
class Solution {
public:
string decodeString(string s) {
if(s.empty())
return "";
stack<int> num;
stack<string> str;
string result="";
int count=0;
string t="";
for(int i=0;i<s.size();i++)
{
if(s[i]>='0'&&s[i]<='9')
{
count=count*10+s[i]-'0';
}
else if(s[i]=='[')
{
num.push(count);count=0;
str.push(t);t="";
}
else if(s[i]==']')
{
int k=num.top();num.pop();
for(int j=0;j<k;j++) str.top()+=t;
t=str.top();str.pop();
}
else
{
t+=s[i];
}
}
return t;
}
};