27 lines
553 B
C++
27 lines
553 B
C++
#include "s0020_valid_parentheses.hpp"
|
|
|
|
bool S0020::match(string s1, string s2) {
|
|
return s1 == "(" && s2 == ")" ||
|
|
s1 == "[" && s2 == "]" ||
|
|
s1 == "{" && s2 == "}";
|
|
}
|
|
|
|
// 直接用栈
|
|
|
|
bool S0020::isValid(string s) {
|
|
stack<string> stack;
|
|
int len = s.length();
|
|
for (int i{0}; i < len; i++) {
|
|
if (stack.empty()) {
|
|
stack.push(s.substr(i, 1));
|
|
} else {
|
|
if (match(stack.top(), s.substr(i, 1))) {
|
|
stack.pop();
|
|
} else {
|
|
stack.push(s.substr(i, 1));
|
|
}
|
|
}
|
|
}
|
|
return stack.empty();
|
|
}
|