题目:
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/decode-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一:
class Solution {
public:
string decodeString(string s) {
stack<int> nums;
stack<char> q;
stack<char> q1;
string str;
int num=0;
int index=0,multi=0;
int len=s.length();
char a,b;
//cout<<s[len-1]<<endl;
for(int i=0;i<len;i++){
a=s[i];
if(a>='0'&&a<='9'){
//cout<<14;
num=num*10+(a-'0');
//cout<<num<<endl;
}
else if(isalpha(a))//头文件cctype
{
q.push(a);
}
else if(a=='['){
nums.push(num);
num=0;
q.push(a);
}
else{
//cout<<33<<endl;
multi=nums.top();
cout<<multi;
nums.pop();
while(q.top()!='['){
b=q.top();
str+=b;
q.pop();
}
for(int i=0;i<multi;i++){
while(index<str.length()){
b=str[index++];
q1.push(b);
}
index=0;
}
q.pop();
index=0;
str="";
while(!q1.empty()){
b=q1.top();
q1.pop();
q.push(b);
}
}
}
while(!q.empty()){
// cout<<42<<endl;
b=q.top();
q.pop();
q1.push(b);
}
while(!q1.empty()){
// cout<<48<<endl;
b=q1.top();
q1.pop();
str+=b;
}
return str;
}
};
体会:自己没有好的思路就看答案吧,别浪费时间写这种全是bug的代码。算是得了个教训。
改进:(不再以字符为操作对象,以字符串为操作对象)
class Solution {
//res记录当前[到下一个[的字符串
//stack<string>保存的是前一个[的字符串
public:
string decodeString(string s) {
stack<string> str;
stack<int> nums;
string res="";
int num=0,multi=0;
for(int i=0;i<s.length();i++){
if(s[i]>='0'&&s[i]<='9'){
num=num*10+(s[i]-'0');
}
else if(isalpha(s[i])){
res=res+s[i];
}
else if(s[i]=='['){
nums.push(num);
str.push(res);
num=0;
res="";
}
else{
multi=nums.top();
nums.pop();
for(int j=0;j<multi;j++){
str.top()+=res;
}
res=str.top();
str.pop();
}
}
return res;
}
};
解法3: