字符串去掉[ ]
规则:[3|AC]——>ACACAC
HGI[3|AC[2|B]]KG[2|F[2|BC]]hj——>HGIACBBACBBACBBKGFBCBCFBCBChj
解决:这种需要递归解决的,一般两种办法,深度优先搜索或者用栈来模拟
#include <iostream>
#include <stack>
using namespace std;
string change(string &str){
string res;
stack<char> op; //存储左括号
stack<int> nums; //存储数字
stack<string> step; //存储每一步去掉[]后的结果
string temp; //存储当前步的结果
for(int i=0;i<str.size();i++){
if(str[i]=='['){
op.push(str[i]);
if(temp.size()){ //压入上一步的结果
step.push(temp);
temp="";
}
}
else if(str[i]>='1'&&str[i]<='9'){
int j=i+1;
int num=str[i]-'0';
while(j<str.size()&&str[j]>='0'&&str[j]<='9'){
num=num*10+(str[j]-'0');
}
nums.push(num);
i=j-1;
}
else if(str[i]=='|'){
}
else if(str[i]==']'){
if(temp.size()) { //关键一步
step.push(temp);
temp="";
}
int num=nums.top();
nums.pop();
string tem=step.top();
step.pop();
//cout<<num<<" "<<tem<<endl;
string ans;
while(num--){
ans+=tem;
}
tem=ans;
if(step.size()){ //加上上一层的结果
auto t=step.top();
step.pop();
t+=tem;
tem=t;
}
step.push(tem);
op.pop();
}
else{
if(nums.size()){ //记录每层的结果
temp+=str[i];
}
if(op.empty()&&step.size()){ //已经解析完[]
res+=step.top();
step.pop();
if(op.empty()){ //关键一步,及]后的一个字符
res+=str[i];
}
}
else if(op.empty()){ //加上不在[]中的字符
res+=str[i];
}
}
}
return res;
}
int main(){
string str;
cin>>str;
cout<<change(str)<<endl;
return 0;
}
结果: