首页 > 代码库 > Week 1 # E Parentheses Balance

Week 1 # E Parentheses Balance

原题描述:

 

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