1. 程式人生 > >Week 1 # E Parentheses Balance

Week 1 # E Parentheses Balance

stdio.h sin -m rect itl file 題目 max ret

原題描述:

E - Parentheses Balance

Parentheses Balance

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

題目就是想讓我們判斷一下兩種括號是否平衡。註意空字符也是平衡的。

這裏要判斷換行輸出Yes,就要用getline(cin,a).還要註意的是,前面幾組數據那裏也有個換行。要用getchar()消除掉;然後就是棧的應用了。

AC代碼:

 1 #include <iostream>
 2 #include <stack>
 3 #include <string.h>
 4 #include <stdio.h>
 5 using namespace std;
 6 int main()
 7 {
 8     int t;
 9     cin>>t;
10             getchar();
11     while (t--)
12     {
13         string a;
14         stack<char> c;
15 getline(cin,a); 16 if(a[0]==\n) {cout<<"Yes"<<endl;continue;} 17 c.push(1); 18 for(int i=0;i<a.size();i++) 19 { 20 if (a[i]==(||a[i]==[) c.push(a[i]); 21 else if (a[i]==)) 22 { 23 if(c.top()==() c.pop(); 24 else c.push(0); 25 } 26 else 27 { 28 if (c.top()==[) c.pop(); 29 else c.push(0); 30 } 31 } 32 if(c.top()==1)cout<<"Yes"<<endl; 33 else cout<<"No"<<endl; 34 35 } 36 return 0; 37 }

Week 1 # E Parentheses Balance