题解 P1241 【括号序列】
wflengxuenong · · 题解
写一堆If太麻烦了,我们用一个数组来转换匹配
#include <iostream>
#include <string.h>
#include <string>
#include <stack>
#include<cstdio>
using namespace std;
char s[202],b[202],tj[9]= {'>','}',']',')','0','(','[','}','<'};
int n,fh[250];
//tj,用来匹配的数组,fh,符号,用来替换的数组
void judge() {
stack<int> st;
int i,l,j=0;
scanf("%s",s);
l=strlen(s);
fh['(']=-1;fh[')']=1;fh['[']=-2;fh[']']=2;fh['{']=-3;fh['}']=3;fh['<']=-4;fh['>']=4;
for (i=0; i<l; i++) {
char c=s[i];
if(fh[c]<0) st.push(i);//左括号入栈
else {
if(!st.empty()){
int k=st.top();
if(fh[s[k]]+fh[c]==0)b[i]=b[k]=1,st.pop();//左右括号匹配
}
}
}
for(int i=0; i<l; i++)
if(b[i])cout<<s[i];
else{
int k=fh[s[i]];
if(k<0)cout<<s[i]<<tj[4+k];
else cout<<tj[4+k]<<s[i];
}
}
int main() {
judge();
}