首页 > 技术文章 > NYOJ 2 括号配对问题

frankM 2014-04-19 16:22 原文

链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=2

 

经典的问题,用栈解决。

 

发现如果括号配对的话,栈顶的元素肯定与当前读入的元素匹配。如果出现一次不匹配的情况,直接break输出No即可。

 

 
#include <stdio.h>
#include <string.h>
char data[10002];
char stack[10000];			//栈
int s_top;					//栈顶指针

int s_pop(void)		
{
	return stack[s_top--];
}

void s_push(char c)
{
	stack[++s_top]=c;
}

int main()
{
	int n;
	int i;
	bool ans;
	scanf("%d",&n);
	while(n--)
	{
		memset(data,'\0',sizeof(data));
		scanf("%s",data);
		for (i=0;i<strlen(data);i++)			//把所有的字符串扫描一遍
		{
			if(data[0]==')'||data[0]==']')
			{
				ans=false;
				break;
			}
			if(data[i]=='('||data[i]=='['||s_top==0)
				s_push(data[i]);
			if(data[i]==')')
			{
				if(s_pop()=='(')
					ans=true;			//当前这一层处理完 ,匹配
				else
				{
					ans=false;			//在当前这一层出现不匹配情况
					break;
				}
			}
			if(data[i]==']')
			{
				if(s_pop()=='[')
					ans=true;
				else
				{
					ans=false;
					break;
				}
			}
			

		}
		ans?printf("Yes\n"):printf("No\n");
	}
	return 0;
}        


 

推荐阅读