UVa 673 Parentheses Balance -SilverN

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, (A) and [A] 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





用栈模拟匹配括号

 1 /*UVa 673 Parentheses Balance*/
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<cmath>
 5 #include<cstring>
 6 #include<stack>
 7 using namespace std;
 8 char c[500];
 9 int n;
10 int pd(char q,char e){//匹配 
11     if(q=='(' && e==')')return 1;
12     if(q=='[' && e==']')return 1;
13     return 0;
14 }
15 int main(){
16     scanf("%d\n",&n);
17     while(n--){
18         gets(c);//因为可能读入空串,所以用gets 
19         if(strcmp(c,"\n")==0){//空串合法 
20             printf("Yes");
21             continue;
22         }
23         int flag=0;
24         stack<char>st;
25         int L=strlen(c);
26         for(int i=0;i<L;i++){
27             if(c[i]=='(' || c[i]=='[') st.push(c[i]);//左括号入栈 
28             else{//右括号处理 
29                 if(st.empty()){
30                     flag=1;
31                     break;
32                 }
33                 if(pd(st.top(),c[i])==1) st.pop();
34                 else{
35                     flag=1;
36                     break;
37                     }
38             }
39         }
40         if(flag==1 || !st.empty())printf("No\n");
41         else printf("Yes\n");
42     }
43     return 0;
44 }

 

posted @ 2016-04-26 19:10  Orion_7  阅读(469)  评论(0编辑  收藏  举报