思路
大体思路:数据结构选用栈,读到左括号时入栈,读到右括号时判断是否匹配,匹配则左括号出栈,非括号字符则继续往下读
代码
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool is_match_parentheses(const string& str)
{
stack<char> srr;
for (int i = 0; i < str.length(); ++i) {
if (str[i] == '(') {
srr.push('(');
} else if (str[i] == ')') {
if (!srr.empyt() && srr.top() == '(') {
srr.pop();
} else {
return false;
}
} else {
continue;
}
}
if (srr.empty()) {
return true;
} else {
return false;
}
}
int main()
{
string str;
cin >> str;
if (is_match_parentheses(str)) {
cout << "True" << endl;
} else {
cout << "False" << endl;
}
return 0;
}