题解 P1928 【外星密码】
Drifterming · · 题解
/*我们先找出每个左括号的位置,然后到着从后往前枚举,因为最后一个括号内肯定是没有括号的。找出没一个括号内要解压的子串以及要解压的次数,将子串解压后得到一个新串,然后将左右括号之间的子串删掉,再将解压后得到的串插入。*/
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int sum,num;
int start[105],ended;
string s,temp,now;
int main()
{
cin>>s;
for(int i=0;i<s.length();i++)
{
if(s[i]=='[') //找左括号的位置
{
start[++sum]=i;
}
}
for(int i=sum;i;i--) //从最后一个左括号开始做,因为最后一个括号内肯定没有括号了
{
ended=2;num=0;temp.clear();now.clear(); //ended=2,因为还要加上左右括号
for(int j=start[i]+1;s[j]!=']';j++)
{
if(s[j]>='0'&&s[j]<='9') //要把串复制几遍
{
num=num*10+s[j]-'0';
}
else
{
temp+=s[j];
}
ended++; //右括号的位置
}
for(int j=1;j<=num;j++) //将字串解压
{
now+=temp;
}
s.erase(start[i],ended); //将左右括号以及之间的子串删掉
s.insert(start[i],now); //插入扩展开的串
}
cout<<s;
return 0;
}