遇到左括号入栈,遇到右括号看其与最上方的括号是否匹配,是则出栈,最后看栈是否为空即可
#include<iostream> #include<stack> using namespace std; bool ismatched(string s){ int l=s.length(); stack<char> stk; if(s[0]==')'||s[0]==']'||s[0]=='}') return false; for(int i=0;i<l;i++){ if(s[i]=='('||s[i]=='['||s[i]=='{') stk.push(s[i]); if((s[i]==')'&&stk.top()=='(')||(s[i]==']'&&stk.top()=='[')||(s[i]=='}'&&stk.top()=='{')) stk.pop();
else
return false; } return stk.empty(); } int main(){ string s; cin>>s; if(ismatched(s)) cout<<"y"<<endl; else cout<<"n"<<endl; return 0; }