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;
}
};
本文介绍了一种使用双栈实现的算法,该算法可以解析一种特殊的编码字符串,这种字符串由k[encoded_string]形式组成,其中方括号内的字符串被重复k次。通过使用数字栈和字符串栈,该算法能高效地解析这类编码并还原成原始字符串。
1359

被折叠的 条评论
为什么被折叠?



