题目描述
给定一个字符串,判断其中的括号是否配对。
输入
第一行输入一个数N(0
3 [({])} ([])} ([[](){}])样例输出
No No Yes–提示:利用栈进行入栈出栈匹配
#include<bits/stdc++.h> using namespace std; int main() { int i,n,t; char a[1010]; stack<char>st; cin>>n; while(n--) { while(!st.empty())//判断栈是否为空,若不为空则让其中元素跳出 { st.pop(); } t=0; cin>>a; int l=strlen(a); for(i=0;i<l;i++) { if(a[i]=='('||a[i]=='{'||a[i]=='[') st.push(a[i]); else//判断是否匹配 { if(a[i]=='}') { if(st.empty()) { t=1;break; } else if(st.top()!='{') { t=1;break; } else st.pop(); } if(a[i]==']') { if(st.empty()) { t=1;break; } else if(st.top()!='[') { t=1;break; } else st.pop(); } if(a[i]==')') { if(st.empty()) { t=1;break; } else if(st.top()!='(') { t=1;break; } else st.pop(); } } } if(!st.empty())//判断栈是否为空 t=1; if(t==1) cout<<"No"<<endl; else cout<<"Yes"<<endl; } return 0; }