3 [(]) (]) ([[]()])
No No Yes
代码:
#include <iostream> #include <string.h> #include <stack> using namespace std; char e[10000]; bool match(stack<char> s,char e[],int n) { for(int i=0;i<n;i++) { if(e[i]==‘(‘||e[i]==‘[‘) s.push(e[i]); if(e[i]==‘)‘) { if(s.empty())//栈里没元素遇到‘)‘肯定不能匹配 return 0; else if(s.top()==‘(‘)//匹配,出栈 s.pop(); else return 0; } if(e[i]==‘]‘) { if(s.empty()) return 0; else if(s.top()==‘[‘) s.pop(); else return 0; } } if(s.empty())//匹配成功的条件 return 1; else return 0; } int main() { int t;cin>>t; while(t--) { cin>>e; int len=strlen(e); stack<char>s; if(match(s,e,len)) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }方法二:自己写栈
代码:
#include <iostream> #include <string.h> using namespace std; const int maxn=10000; char e[maxn]; typedef struct { char data[maxn]; int top; }Stack; bool ok(char e[],int n) { Stack s; s.top=-1; for(int i=0;i<n;i++) { if(e[i]==‘(‘||e[i]==‘[‘) s.data[++s.top]=e[i]; if(e[i]==‘)‘) { if(s.top==-1) return 0; else if(s.data[s.top]==‘(‘) s.top--; else return 0; } if(e[i]==‘]‘) { if(s.top==-1) return 0; else if(s.data[s.top]==‘[‘) s.top--; else return 0; } } if(s.top==-1) return 1; else return 0; } int main() { int t;cin>>t; while(t--) { cin>>e; int len=strlen(e); if(ok(e,len)) cout<<"Yes"<<endl; else cout<<"No"<<endl; } return 0; }
[ACM] 括号匹配问题(栈的使用),布布扣,bubuko.com
原文:http://blog.csdn.net/sr_19930829/article/details/22983435