Logo lxn 的博客

博客

题解 P1241 【括号序列】

...
lxn
2025-12-01 12:57:42

本文章由 WyOJ Shojo 从洛谷专栏拉取,原发布时间为 2018-07-05 15:50:15

写一堆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();
}

评论

暂无评论

发表评论

可以用@mike来提到mike这个用户,mike会被高亮显示。如果你真的想打“@”这个字符,请用“@@”。