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;
} 

发布了87 篇原创文章 · 获赞 56 · 访问量 9145

猜你喜欢

转载自blog.csdn.net/Ven21959/article/details/102402503