括号匹配
作者:
三万岁_6
,
2024-07-29 17:27:22
,
所有人可见
,
阅读 1
#include <iostream>
#include <stack>
using namespace std;
bool bracketMatch(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(bracketMatch(s1))
cout << "s1 matched" << endl;
else
cout << "s1 not matched" << endl;
if(bracketMatch(s2))
cout << "s2 matched" << endl;
else
cout << "s2 not matched" << endl;
return 0;
}