码迷,mamicode.com
首页 > 其他好文 > 详细

UVa 673 Parentheses Balance【栈】

时间:2015-04-20 16:19:48      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:

题意:输入一个包含"()"和"[]"的序列,判断是否合法

用栈来模拟,遇到"(",“[”就入栈,遇到‘)‘,‘]‘就取出栈顶元素看是否匹配,如果不匹配,则不合法

还有注意一下每次取出栈顶元素的时候判断栈是否为空,如果为空就要跳出循环

注意空串也是合法的串

技术分享
 1 #include<iostream>  
 2 #include<cstdio>  
 3 #include<cstring> 
 4 #include <cmath> 
 5 #include<stack>
 6 #include<vector>
 7 #include<map> 
 8 #include<set>
 9 #include<queue> 
10 #include<algorithm>  
11 using namespace std;
12 
13 typedef long long LL;
14 const int INF = (1<<30)-1;
15 const int mod=1000000007;
16 const int maxn=100005;
17 char t[maxn];
18 
19 int main(){
20     int ncase;
21     scanf("%d",&ncase);
22     getchar();
23     while(ncase--){
24         stack<char> s;
25         gets(t);
26         int len=strlen(t);
27         int flag=1;
28         for(int i=0;i<len;i++){
29             if(t[i]==(||t[i]==[) s.push(t[i]);
30             
31         //    printf("s.size()=%d\n",s.size());
32             else  if(t[i]==)){
33                 if(s.size()==0) {
34                     flag=0;
35                     break;
36                 }
37                 char ch=s.top();s.pop();
38                 if(ch!=() flag=0;            
39             }
40             else{
41                 if(s.size()==0){
42                     flag=0;
43                     break;
44                 }
45                 char ch=s.top();s.pop();
46                 if(ch!=[) flag=0;
47             }
48             if(flag==0) break;
49         }
50         
51         if(s.size()!=0) flag=0;
52         if(flag) printf("Yes\n");
53         else printf("No\n");        
54     }
55     return 0;
56 }
View Code

 

UVa 673 Parentheses Balance【栈】

标签:

原文地址:http://www.cnblogs.com/wuyuewoniu/p/4441645.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!