【字符串转换】字符串去掉[ ]

字符串去掉[ ]

规则:[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;
}

 结果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

烊萌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值