题解 | 括号配对问题
括号配对问题
https://www.nowcoder.com/practice/57260c08eaa44feababd05b328b897d7
#include <iostream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
bool is_value(const vector<char>& v) {
stack<char> s;
for (const auto& c : v) {
if (c == '(' || c == '[') {
s.push(c);
} else {
if (s.empty()) {
return false;
}
char top = s.top();
s.pop();
if ((c == ')' && top != '(') || (c == ']' && top != '[')) {
return false;
}
}
}
return s.empty();
}
bool check(const string& s) {
vector<char> v;
for (const auto& c : s) {
if (c == '(' || c == ')' || c == '[' || c == ']') {
v.push_back(c);
}
}
return is_value(v);
}
int main() {
string s;
cin >> s;
cout << (check(s) ? "true" : "false") << endl;
return 0;
}
查看26道真题和解析
