括号匹配--nyoj 2

括号配对问题

时间限制:3000 ms  |  内存限制:65535 KB
难度:3
 
描述
现在,有一行括号序列,请你检查这行括号是否配对。
 
输入
第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
输出
每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
样例输入
3
[(])
(])
([[]()])
样例输出
No
No
Yes
来源
网络
上传者
naonao
 1 #include<stdio.h>
 2 #include<string.h>
 3 int main()
 4 {
 5     int k,top;
 6     int N,i,l;
 7     char s1[10005],s2[10005];
 8     scanf("%d",&N);
 9     getchar();
10     while(N--)
11     {
12         gets(s1);
13         l=strlen(s1);
14         if(l%2==1)
15             printf("No");
16         else
17         {
18             top=1;
19             s2[top]=s1[0];
20             for(i=1;i<l;i++)
21             {//判断 s1 是否匹配 逐一进行匹配 实行:先进的后匹配原则 如果匹配则将其弹出 否则压入s2中
22                 if((s1[i]==')' && s2[top]=='(') || (s1[i]==']'&&s2[top]=='['))
23                     top--;//弹出栈顶
24                 else
25                     s2[++top]=s1[i];//元素压入
26             }
27             if(top==0) printf("Yes");
28             else printf("No");
29         }
30         printf("\n");
31     }
32     return 0;
33 }
View Code

数组来模拟栈的思想  先进后出原则  先进的后匹配 逐一进行与栈顶进行匹配 匹配的弹出栈顶  不匹配的压入栈  最后判断栈是否为空即栈顶是否为0即为全部匹配

 

 1 /*
 2 #include<cstring>
 3 #include<stack>
 4 #include<iostream>
 5 #include<algorithm>
 6 using namespace std;
 7 int main()
 8 {
 9     int n, i;
10     cin >> n;
11     while(n--)
12     {
13         char str[10005];
14         stack<char> s;
15         while(!s.empty()) s.pop();
16         cin >> str;
17         int len = strlen(str);
18         if(len % 2 == 1)
19             cout << "No" << endl;
20         else
21         {
22             s.push(str[0]);
23             for(i = 1; i < len; i++)
24             {
25                 if((str[i] == ')' && s.top() == '(') || (str[i] == ']' && s.top() == '['))
26                     s.pop();
27                 else
28                     s.push(str[i]);
29             }
30             if(!s.empty())
31                 cout << "No" << endl;
32             else
33                 cout << "Yes" << endl;
34         }
35     }
36     return 0;
37 }*/
View Code

 

直接调用系统栈

 

posted on 2014-01-12 17:09  yun_  阅读(229)  评论(0编辑  收藏  举报