问题描述:
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/decode-string
示例:
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
解题思路:
使用栈,开辟一个int型栈和string栈
使用变量num和str,
当遇到'['字符时,将num压入int栈,同时num重置0
遇到']'字符时,取出num栈顶元素k,tempstr = k*str; string栈顶元素变为 top()+tempstr
完整代码如下:
class Solution {
public:
string decodeString(string s) {
int len = s.size();
int num = 0;
stack<int> numstack;
stack<string> strstack;
string cur ="";
string res ="";
for(int i=0;i<len;i++){
if(s[i]>='0' && s[i]<='9'){
num = 10*num+s[i]-'0';
}
else if(s[i]=='['){
numstack.push(num);
strstack.push(cur);
num = 0;
cur.clear();
}
else if((s[i]>='A'&& s[i]<='Z')||(s[i]>='a'&&s[i]<='z')){
cur+=s[i];
}
else if(s[i]==']'){
int k = numstack.top();
numstack.pop();
string temp ="";
for(int j=0;j<k;j++){
temp +=cur;
}
string str = strstack.top();
cur = str+temp;
strstack.pop();
}
}
res = cur;
return res;
}
};