一个用栈实现的括号匹配

发布时间 2023-05-27 12:14:08作者: 未晞之时
#include<iostream>
#include<cstring>
#include<stack> using namespace std; int main(){ string input; cin>>input; int a=input.length(); stack <char> stk; if(a%2 != 0){ cout<<"False"<<endl; return 0; } for(int i=0;i<a;i++){ char ch = input[i]; if(ch == '{' || ch == '(' || ch =='['){ stk.push(ch); } else{ if(ch=='}'){ if(stk.top() == '{'){ stk.pop(); } else{ cout<<"False"<<endl; return 0; } } if(ch==']'){ if(stk.top() == '['){ stk.pop(); } else{ cout<<"False"<<endl; return 0; } } if(ch==')'){ if(stk.top() == '('){ stk.pop(); } else{ cout<<"False"<<endl; return 0; } } } } if(stk.empty()){ cout<<"True"<<endl; } else{ cout<<"False"<<endl; } return 0; }

将左括号压入栈 判断是否匹配 匹配则删除 最后判断栈是否为空