394. 字符串解码
给定一个经过编码的字符串,返回它解码后的字符串
示例:
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
解题思路:
用栈保存字符,遇到右括号停止,将与它对应的左括号之间的字符进行解码,然后压栈;如此循环,直到解完为止。
没有考虑到的点:
1、数字可能是多位的,例如:“100[leetcode]”;
2、取栈顶的时候注意栈是否为空,否则会溢出;
3、栈是反顺序,需要时刻关注取出的字符串的顺序;
#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;
string decodeString(string s) {
string res;
if(s.empty())
return res;
stack<char> s1;
for(auto i:s){
string tmp;
if(i == ']'){
while(s1.top() != '['){
tmp = s1.top() + tmp;
s1.pop();
}
s1.pop();
string snum;
//取数字的时候要关注是否已到栈底
while(!s1.empty() && isdigit(s1.top())){
snum += s1.top();
s1.pop();
}
reverse(snum.begin(),snum.end());
//字符串转数字用stoi函数
int num = stoi(snum);
string str;
while(num > 0){
str += tmp;
num--;
}
for(auto j:str){
s1.push(j);
}
}else {
s1.push(i);
}
}
while(!s1.empty()){
res += s1.top();
s1.pop();
}
reverse(res.begin(),res.end());
return res;
}