平衡的括号

题目:

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

 题意:

    给出一个由括号()和[]组成的字符串。下例类型的字符串是正确的:
(1)
如果它是空字符串
(b)
如果A和B是正确的,AB是正确的,
(c)
如果是A正确的,(A)和[A]是正确的。
思路:

   先输入一个数组并且创建一个栈,后遍历数组中的字符,如果是'('或'['时就入栈,如果等于栈顶就将栈顶的字符删除;

最后判断栈是否为空,为空输出Yes,否则为No。

注意当数组为/n是输出Yes。

相关知识:

栈提供了如下的操作

  1. s.empty()               如果栈为空返回true,否则返回false  
  2. s.size()                返回栈中元素的个数  
  3. s.pop()                 删除栈顶元素但不返回其值  
  4. s.top()                 返回栈顶的元素,但不删除该元素  
  5. s.push()                在栈顶压入新元素  
 1 #include<iostream>
 2 #include<stack>
 3 #include<cstdio>
 4 #include<cstring>
 5 using namespace std;
 6 int main()
 7 {
 8 int t,i;
 9 char b[150];
10 cin>>t;
11 getchar();
12 while(t--)
13 {
14 stack<char>a;
15 gets(b);
16 if(strcmp(b,"/n")==0)
17 {cout<<"Yes"<<endl;
18 continue;
19 }
20 for(i=0;b[i];)
21 {if(a.empty())
22      a.push(b[i]);
23  else   if((a.top()=='('&&b[i]==')')||(a.top()=='['&&b[i]==']'))
24           a.pop();
25             else  
26                 if(b[i]=='('||b[i]=='[')
27                     a.push(b[i]);
28                 i++;
29 }               
30 if(a.empty())
31 cout<<"Yes"<<endl;
32 else  cout<<"No"<<endl;
33 }
34 return 0;
35 }

 

posted @ 2015-07-22 21:04  枫虹  阅读(250)  评论(0编辑  收藏  举报