ACM 括号配对问题

括号配对问题

时间限制:3000 ms  |  内存限制:65535 KB
难度:3
描述
现在,有一行括号序列,请你检查这行括号是否配对。
输入
第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
输出
每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
样例输入
3
[(])
(])
([[]()])
样例输出
No
No
Yes

程序代码:


 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 struct Stack{
 5     char *stack;
 6     int top;
 7 };
 8 void init(Stack &S){                 //初始化栈
 9     S.stack=new char[10000];
10     S.top=-1;
11 }
12 void Push(Stack &S,char &ch){        //入栈
13     S.top++;
14     S.stack[S.top]=ch;
15 }
16 void Pop(Stack &S){                   //出栈
17     S.top--;
18 }
19 int Peek(Stack &S){                   //此方法类似于 Pop 方法,但 Pop 不修改 Stack
20     return S.stack[S.top];
21 }
22 int main(){
23     Stack S;
24     string str;
25     int x,d,i;cin>>d;
26     while(d--){
27         init(S);
28         cin>>str;x=0;                                        
29         for(i=0;i<str.size();i++){
30             switch(str[i]){
31                 case '[':
32                 case '(':Push(S,str[i]);break;
33                 case ']':if(Peek(S)=='[') Pop(S);else x=1;break;
34                 case ')':if(Peek(S)=='(') Pop(S);else x=1;break;
35                 }
36             if(x==1) break;
37         }
38         if(S.top==-1&&x==0) cout<<"Yes"<<endl;
39         else cout<<"No"<<endl;
40         delete[] S.stack;
41     }
42 }
原文地址:https://www.cnblogs.com/HRuinger/p/3599206.html