括号配对(南阳理工2)栈
2016-04-22 16:26
155 查看
括号配对问题
时间限制:3000 ms | 内存限制:65535 KB难度:3
描述现在,有一行括号序列,请你检查这行括号是否配对。
输入第一行输入一个数N(0<N<=100),表示有N组测试数据。后面的N行输入多组输入数据,每组输入数据都是一个字符串S(S的长度小于10000,且S不是空串),测试数据组数少于5组。数据保证S中只含有"[","]","(",")"四种字符
输出每组输入数据的输出占一行,如果该字符串中所含的括号是配对的,则输出Yes,如果不配对则输出No
样例输入
3 [(]) (]) ([[]()])
样例输出
No No Yes
栈的应用
#include <iostream> #include <cstdio> #include <cstring> #include <string> #include <algorithm> using namespace std; char s[10055]; char a[10005]; int fun(char x,char y )//判断栈顶元素与将要入栈的元素是否可以配对。 { if(x=='('&&y==')') return 1; else if(x=='['&&y==']') return 1; else return 0; } int main() { int n; scanf("%d",&n); while(n--) { scanf("%s",s); int top=-1; int d=strlen(s); if(d%2!=0) printf("No\n");//如果长度为奇的话则表示无法配对成功 else { a[++top]=s[0]; for(int i=1; i<d; i++) { if(fun(a[top],s[i])) { top--; //如果配对成功出栈 } else { top++; a[top]=s[i]; //否则继续入栈 } } if(top<0) printf("Yes\n");//如果栈为空则表示可以配对成功 else printf("No\n"); } } return 0; }
或者:
(2)第二种方法(栈) #include <iostream> #include <algorithm> #include <cstdio> #include <stack> using namespace std; stack <char>s; bool cmp(char a,char b) { return (a=='['&&b==']')||(a=='('&&b==')'); } int main() { int t; cin>>t; getchar(); char str[10010]; while(t--) { gets(str); while(!s.empty()) s.pop(); int i; for(i=0;str[i]!='\0';i++) { if(s.empty()||!cmp(s.top(),str[i])) s.push(str[i]); else s.pop(); } if(s.empty()) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }
相关文章推荐
- 在Word中如何自动生成参考文献引用
- BP神经网络的网络带宽预测
- django/python日志logging 的配置以及处理
- 华为交换机板卡端口型号对照
- 快吧游戏盒官方下载2016 v4.0.5.6959 官方最新版
- 数据持久化,一个简单的hibernate例子
- Java权限管理之Spring Security
- opencv:累加图像求平均(c语言版本)
- php统计文件夹所有文件 及 容量大小
- BZOJ2391: Cirno的忧郁
- C++第四次作业
- struts1学习
- hibernate在crud时拦截
- -std=c++11
- 朴素贝叶斯算法Python实现
- windows下Python图形化工具Matplotlib安装
- 一篇关于arc下内存管理的老文章,包括各种冷门修饰符(关于内存),写的较好,mark
- Android蓝牙初级一
- easyUI
- 基因数据处理20之BWASW算法ref分块建立索引然后比对