NYOJ2(括号匹配)

#include <stdio.h>
int main()
{
	int z;
	scanf("%d",&z);
	while(z--)
	{
		char ch,s[10001];
		int top=-1;
		while((ch=getchar())!='\n')//中间没有空格
		{
			if(ch==')' && top>=0 && s[top]=='(')//top>=0表明栈不空
				top--;
			else 
				if(ch==']' && top>=0 && s[top]=='[')
					top--;
				else 
					s[++top]=ch;
	}
		if(top==-1)
			puts("Yes");
		else
			puts("No");
	}
	return 0;
} 
//左括号的话入栈,右括号的话要么与栈顶配对要么错误 ,开始结束时栈要为空

 

#include<stdio.h>
#include<string.h>
char str[10001];
int main()
{
	int i,j,T;int top=-1,len;
	scanf("%d%*c",&T);
	while(T--)
	{
		top=0;
		memset(str,0,sizeof(str));
		scanf("%s",str);
		len=strlen(str);
		for(i=1;i<len;i++)
		{
			if(str[i]==')'&&str[top]=='('&&top!=-1)
				top--;
			else if(str[i]==']'&&str[top]=='['&&top!=-1)
				top--;
			else
				str[++top]=str[i];
		//	printf("%d     %d\n",i,top);
		}
		if(top==-1)
			puts("Yes");
		else
			puts("No");
		
	}
	return 0;
}

 

原文地址:https://www.cnblogs.com/hxsyl/p/2503794.html