leetcode 394. 字符串解码(栈)
题目链接
https://leetcode-cn.com/problems/decode-string/
题意:
给定一行字符串,判断经过k[encoded_string]编码规则后的结果
思路:
把每一层的字符串,以及出现的次数放在栈里面
最后记录拼接完成后的结果
难点在于怎么同时记录嵌套的关系,比如3[a2[bc]4[d]]
class Solution {
public:
//注意局部的tmp 更新与全局tmp更新的关系
//不直观,不好想
//每次把之前处理好的放在栈里
string decodeString(string s) {
stack<string> S;
stack<int> S2;
int num=0;
string tmp="";
string ans="";
for(int i=0;i<s.size();i++){
char cur=s[i];
if(isdigit(cur)){//数字
num=num*10+cur-'0';
}
else if(isalpha(cur)){
tmp+=cur;
}
else if(cur=='['){
S2.push(num);
num=0;
S.push(tmp);
tmp="";
}
else{
//前面部分的字符串
// string pre="";
// if(S2.size()>1){
// pre=S.top();
// S.pop();
// }
int tmp_n=S2.top();
S2.pop();
// string tmp_s="";
string tp=S.top();
S.pop();
for(int i=1;i<=tmp_n;i++){
// tmp_s+=tmp;
tp+=tmp;//不好想 3[a2[cc]]
}
tmp=tp;//不好想
// pre+=tmp_s;
// cout<<pre<<"\n";
// S.push(pre);
// if(!S2.size()) ans+=pre;
}
}
ans=tmp;
return ans;
}
};