ZOJ-2571 Big String Outspread 模拟

本文介绍了一种处理特定格式字符串的方法,通过递归解析字符串中的数字、括号及字符,实现字符串的展开与重复。该算法适用于字符串解析任务,如配置文件解析等。

题意:给定一个字符串,按照要求输出来。

解法:每次进行一次首字母判定,然后根据不同的情况进行递归。

代码如下:

#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

char str[300];

string display(int ti, int sta, int fuck) {
    string ret;
    if (sta > fuck) return ret;
    if (sta == fuck && !isalpha(str[sta])) return ret;
    string tmp;
    if (!isalpha(str[sta])) { // 如果不是以字符开始
        if (isdigit(str[sta])) {
            int t = 0, i, j;
            for (i = sta; isdigit(str[i]); ++i) { // 如果是数字的话 
                t = t * 10 + (str[i] - '0'); // 得出循环的次数数字
            }
            if (str[i] != '(') { // 如果后面不是括号,那么只有一位 
                tmp = display(t, i, i) + display(1, i+1, fuck);
            } else {
                int cnt = 0;
                for (j = sta; ; ++j) { // 找到括号在的位置 
                    if (str[j] == ')') {
                        --cnt;
                        if (!cnt) break;
                    }
                    else if (str[j] == '(') ++cnt;
                }
                tmp = display(t, i+1, j-1) + display(1, j+1, fuck);
            }
        }
        else { // 如果是括号进入 
            int cnt = 0, j;
            for (j = sta; ; ++j) {
                if (str[j] == ')') {
                    --cnt;
                    if (!cnt) break;    
                }
                else if (str[j] == '(') ++cnt;
            }
            tmp = display(1, sta, j-1) + display(1, j+1, fuck);
        }
        while (ti--) {
            ret += tmp;
        }
    } else {
        tmp = str[sta] + display(1, sta+1, fuck);
        while (ti--)
            ret += tmp; // 把后面的这一个字母进行重复
    }
    return ret;
}

int main() {
    int T, len;
    scanf("%d", &T);
    while (T--) {
        scanf("%s", str);
        len = strlen(str);
        cout << display(1, 0, len-1) << endl;
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值