解码字符串

表达式S,只包含数字字母以及方括号,该表达式有如下规则:数字只会出现在方括号之前,它表示方括号里内容的重复次数

按上述规则展开字符串

示例1 

e3[2[abc]gh]

eabcabcghabcabcghabcabcgh

示例2

e9[xyz]

exyzxyzxyzxyzxyzxyzxyzxyzxyz      

示例3

e3[a2[abc]gh]

eaabcabcghaabcabcghaabcabcgh

#include <stack>
#include <stdio.h>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

/*
    遍历字符串S
    遇到'['以及字母入栈
    遇到数字则先入栈一个'*',用于分割这个括号左边的子串与右边的子串
    遇到']'则先将']'之前的字母取出并倒序,然后链接到答案右边 再按重复规则重复 再将*之前的字母取出倒序链接到答案左边(这里不重复左边是因为不包含在括号内)


*/

//./test   e9[xyz]   e3[a2[abc]gh]  e3[2[abc]gh]
int main(){
	string S;
	while(cin>>S){
		stack<char> T;
		int n = S.length();
		string ans = "";
		int num=0;
		for(int i=0;i<n;i++){
			if(S[i]==']'){
				num++;
				//cout<<"处理第"<<num<<"对括号"<<endl;
				string left="",right="";
				while(T.top()!='['){
					right+=T.top();
					//cout << right << ",";
					T.pop();
				}
				T.pop();
				//倒序child
				reverse(right.begin(),right.end());
				cout << right << endl;
				string now_ans;
				int n = T.top()-'0';T.pop();
				//cout << n<<endl;
				//cout << "??"<<T.top()<<endl;
				if(T.top()=='*'){
					T.pop();
					if(!T.empty()){
						while(!T.empty() and T.top()!='['){
							left+=T.top();
							cout << left << ",";
							T.pop();
						}
						if(left.length()!=0)
							reverse(left.begin(),left.end());cout << left << endl;
					}
				}
				now_ans = ans+right;
				//cout << "2:"<<now_ans << endl;
				string last_ans = "";
				
				for(int j=0;j<n;j++)
					last_ans+=now_ans;
				ans = left+last_ans;
				//cout << "处理后的结果"<<ans << endl;
			}else{
				if(S[i]<='9' and S[i]>='0')
					T.push('*');
				T.push(S[i]);
			}
		}
		while(!T.empty()){
			char c = T.top();T.pop();
			ans = c+ans;
		}
		cout << ans <<endl;

	}
	return 0;
}
发布了18 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_33500066/article/details/88956884
今日推荐