Parentheses Balance(673)

You are given a string consisting of parentheses () and []. A string of this type is said to be correct:

(a)
if it is the empty string
(b)
if A and B are correct, AB is correct,
(c)
if A is correct, () and [] is correct.

Write a program that takes a sequence of strings of this type and check their correctness. Your program can assume that the maximum string length is 128.

Input 

The file contains a positive integer n and a sequence of n strings of parentheses () and [], one string a line.

Output 

A sequence of Yes or No on the output file.

Sample Input 

3
([])
(([()])))
([()[]()])()

Sample Output 

Yes
No

Yes

注:用堆棧,是(,[就入棧,),]就出

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <set>
#include <list> 
#include <map> 
#include <string>
using namespace std; 
#define infinity 2147483647
int gcd(int a,int b)
{
	return b==0?a:gcd(b,a%b);
}

int main()
{
	int n,i,l,flag;
	char s[1000];
	stack<char>ss;
	while(scanf("%d",&n)!=EOF)
	{
		getchar();
		while(n--)
		{
			gets(s);
			
			while(!ss.empty())
			{
				ss.pop();
			}
			
			flag=1;
			l=strlen(s);	
			for(i=0;i<l;i++)
			{
				if(s[i]=='(' || s[i]=='[')
				ss.push(s[i]);
				else if(s[i]==')')
				{
					if(ss.empty())
					{
						flag=0;
						break;
					}
					else if(ss.top()=='(')
					ss.pop();
					else
					{
						flag=0;
						break;
					}
				}	
				else if(s[i]==']')
				{
					if(ss.empty())
					{
						flag=0;
						break;
					}
					else if(ss.top()=='[')
					ss.pop();
					else
					{
						flag=0;
						break;
					}
				}
			}
			if(flag && ss.empty())
			cout <<"Yes" <<endl;
			else
			cout <<"No" <<endl;			
		}
	}	
			
	return 0;
}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章