思路
起初看到这题的时候,一脸懵逼不知道该怎么写,我是这么想的一来就把所有的数据都输入,但是然后就不知道怎么写了。
当我看到别人的思路才没明白,原来一个一个输入才是正确的。
1.先寻找左括号,然后输入次数,再把次数叠加(再次递归,因为继续输入的不是左括号,右括号,直接加上去就行了)
2.找到了右括号,则直接返回就行。
源码
#include<bits/stdc++.h>
using namespace std;
string fun(){
int n;
string s="",s1;
char c;
while(cin>>c){ //读入一个字母
if(c=='['){ //若为左括号,则输入继续输入
cin>>n;
s1=fun();
while(n--) s+=s1;
}
else
{
if(c==']') return s; //匹配到右括号,则返回。
else s+=c;
}
}
}
int main(){
cout<<fun();
return 0;
}
源码
//运用栈,判断 [ 和数字
//递归
#include<bits/stdc++.h>
using namespace std;
string expand(){
string s="",X;
char c;int D;
while(cin>>c){
if(c=='['){
cin>>D; //输入完数字后,则到 ] 都要输入,用X来存储
X = expand();
while(D--) s +=X;//数字是几,则扩大几倍
}
else if(c==']') return s; //结束条件
else s+=c; //存储数字后的字符 返回后,则存于X里
}
return s;
}
int main(){
cout<<expand()<<endl;
return 0;
}