题目描述:
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].
Examples:
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) {
stack<string> str;
stack<int> k;
string result;
int count=0;
for(int i=0;i<s.length();i++)
{
if((s[i]<='z'&&s[i]>='a')||(s[i]>='A'&&s[i]<='Z')) result+=s[i];
else if(s[i]>='0'&&s[i]<='9')
{
count*=10;
count+=s[i]-'0';
}
else if(s[i]=='[')
{
k.push(count);
count=0;
str.push(result);
result="";
}
else if(s[i]==']')
{
int times=k.top();
k.pop();
for(int j=0;j<times;j++) str.top()+=result;
result=str.top();
str.pop();
}
}
return result;
}
};
957



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



