F题 Sequence Decoding

National Contest for Private Universities (NCPU), 2019

 

题意:[ ]内的字符,重复前面的数字次,输出最终结果

 

方法一:dfs循环

#include<bits/stdc++.h>
using namespace std;
char *dfs(char s[]) {
	char *p;
	while(1) {
		int k=0;
		while(isdigit(*s)) {
			k = k*10+(*s-'0'); // [前面数字不一定为个位 
			s++;
		}
		if(k==0)
			k++;
		if(*s=='[') {
			for(int i=0;i<k;i++)
				p=dfs(s+1);
			s=p;
		} 
		else if(*s=='P' || *s=='H') {
			for(int i=0;i<k;i++)
				cout<<*s;
			s++;
		}
		else
			return s+1;
	}
}

int main() {
	int T;
	cin >> T;
	while(T--) {
		char str[1100];
		cin>>str;
		dfs(str);
		cout<<endl;
	}
	return 0;
}

isdigit():如果一个字符是0—9的任意一个,即是数字的话,返回true,不是数字返回false

 

 

方法二:栈模拟

#include<bits/stdc++.h>
using namespace std; 
int	main() {
	int T;
	cin >> T;
	while(T--) {
		stack<int> st;
		string s,p;
		cin >> s;
		for(int i=0;i<s.size();i++) {
			if(s[i]!=']')
				st.push(s[i]);
			else {
				string c;
				while(st.top()!='[') {
					c += st.top();
					st.pop();
				}
				reverse(c.begin(),c.end());//LIFO 
				st.pop();
				int num = (int)(st.top()-'0'); 
				st.pop();
				for(int j=1;j<=num;j++) 
					for(int k=0;k<c.size();k++)
						st.push(c[k]);
			}
		}
		while(st.size()) {
			p += st.top();
			st.pop();
		}
		reverse(p.begin(),p.end());
		cout<<p<<endl;
	} 
	return 0;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值