AcWing 3693. 括号匹配
原题链接
简单
//遍历字符串,遇到右括号入栈
//遇到左括号出栈并与之对比
//判断栈是否为空,为空则括号匹配
#include <iostream>
#include <stack>
using namespace std;
bool brackMatch(string str){
stack<char> s;
for(char c:str)
if(c =='(' || c == '[' || c == '{')
s.push(c);
else{
if(s.empty()) return false;
char top = s.top();
s.pop();
if(c == ')' && top != '(' || c == ']' && top != '[' || c == '}' && top != '{' )
return false;
}
return s.empty();
}
int main(){
string s1="[[[[]]]]";
string s2="[[[[(]]]]]";
if(brackMatch(s1))
cout<<"s1 matched" <<endl;
else
cout<<"s1 not matched" <<endl;
if(brackMatch(s2))
cout<<"s2 matched" <<endl;
else
cout<<"s2 not matched" <<endl;
return 0;
}
// int main(){
// string s;
// cin>>s;
// if(brackMatch(s))
// cout<<"no" <<endl;
// else
// cout<<"yes" <<endl;
// }