hdu 1274 展开字符串

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=1274

一开始solve没有返回位置,然后递归的时候就出错了。。。

STL特别好用。。。

View Code
 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 int  solve(string &str,string &restr,int pos){
 6     int len=str.length();
 7     while(pos<len){
 8         //是字母
 9         if(str[pos]>='a'&&str[pos]<='z'){
10             restr.push_back(str[pos]);
11         }else if(str[pos]>='0'&&str[pos]<='9'){                        //是数字
12             int count=0;
13             while(pos<len&&str[pos]>='0'&&str[pos]<='9'){
14                 count=10*count+str[pos]-'0';
15                 pos++;
16             }
17             //后面是字母
18             if(str[pos]>='a'&&str[pos]<='z'){
19                 for(int i=1;i<=count;i++){
20                     restr.push_back(str[pos]);
21                 }
22             }else if(str[pos]=='('){                     //后面是括号
23                 string temp;
24                 pos=solve(str,temp,pos+1);
25                 for(int i=1;i<=count;i++){
26                     restr.append(temp);  //追加
27                 }
28             }
29         }else if(str[pos]=='('){          //是括号
30             string temp;
31             pos=solve(str,temp,pos+1);
32             restr.append(temp);
33         }else if(str[pos]==')'){
34             break;
35         }
36         pos++;
37     }
38     return pos;
39 }
40 
41 int main(){
42     int n;
43     scanf("%d",&n);
44     while(n--){
45         string str,restr;
46         cin>>str;
47         solve(str,restr,0);
48         cout<<restr<<endl;
49     }
50     return 0;
51 }
原文地址:https://www.cnblogs.com/wally/p/2933859.html