ZOJ 2571 Big String Outspread

本文介绍了一种使用递归方法而非栈来解析嵌套括号字符串的技术,并提供了完整的C++实现代码。该方法通过读取输入字符,遇到括号进行递归调用,最终返回展开后的字符串。

看到括号就想到了栈什么的,这题可以用递归展开括号,不需要栈.

#include <iostream>
#include <cstdio>
#include <string>
using namespace std;
string unfold(){
	string ret,tmp;
	char ch;
	int times = 1;
	while ((ch = getchar()) != ')' && ch != '\n'){
		if(isdigit(ch)){
			cin.putback(ch);
			scanf("%d", &times);
		}else{
			if(ch == '('){
				tmp = unfold();
				for (int i = 0; i < times;++i){
					ret +=tmp;
				}
				times = 1;
			}else{
				ret += string(times,ch);
				times = 1;
			}
		}
	}
	return ret;
}
int main(){
	int T;
	scanf("%d\n", &T);
	while (T--){
		printf("%s\n",unfold().c_str());
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值