UVA-Parentheses Balance

90 阅读1分钟

Parentheses Balance

题目链接:

uva.onlinejudge.org/index.php?o…

题意描述:

该题是判断所给的字符串括号是否匹配,如果匹配输出Yes若果是空串也输出Yes否则输出No

解题思路:

该题可以模拟栈的操作,当来一个右括号时,需要判断下左边是否与之相对应,如果对应继续往下比较,否则就结束比较,需要注意的就是空串的时候

程序代码:

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

char str[150],str0[150];

int main() 
{ 
	int i,n,t;
	scanf("%d",&n);
	getchar(); 
	while(n--)
	{
		t=0;
		while(scanf("%c",&str[t]),str[t]!='\n')
		{
			t++;
		}
		str[t]='\0';
		t=0;
		for(i=0;str[i]!='\0';i++)
		{
			str0[t]=str[i];
			if(str0[t]==')'&&str0[t-1]=='('||str0[t]==']'&&str0[t-1]=='[')
				t--;
			else
				t++;
		}
		if(t==0)
			printf("Yes\n");
		else
			printf("No\n");
	}
	return 0;
}