HDU 1274 展开字符串

题目地址: http://acm.hdu.edu.cn/showproblem.php?pid=1274

 

一个很不错的递归题,我主要的过程就如一般的表达式求解,遇到左括号进入下层递归否则一直按每个字母前面的数字决定其输出的次数,括号也是如此,而递归结束的标志/则是遇到 右括号或者到字符串的结尾,注意每次递归结束需要返回下次遍历的序号

 

代码如下:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
using namespace std;

/*
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
*/

int len;
char a[255];

int xiaohao(int k)
{
    int i,e;
    char c;
    for(c=a[k++];k<len&&c!=')';c=a[k++])
    {
        for(i=0;isdigit(c);c=a[k++])
            i=i*10+c-'0';
        if(i==0)
            i=1;
        if(c=='(')
        {
            while(i--)
                e=xiaohao(k);
            k=e;
        }
        else
        {
            while(i--)
                putchar(c);
        }
    }
    if(c==')')
        return k;
}

int main()
{
    int t,i;
    cin>>t;
    while(t--)
    {
        scanf("%s",a);
        len=strlen(a);
        xiaohao(0);
        cout<<endl;
    }
    return 520;
}


 

你可能感兴趣的:(HDU 1274 展开字符串)