class Solution {
public:
//判断左右括号是否配对
bool match(char a, char b) {
if (a == '(' && b == ')' ||
a == '[' && b == ']' ||
a == '{' && b == '}')
return true;
return false;
}
inline bool isLeft(char c) {
if (c == '(' || c == '[' || c == '{') return true;
return false;
}
bool isValid(string s) {
stack<char> chs;
for (int i = 0; i < s.length(); i++) {
if (isLeft(s[i])) {
chs.push(s[i]);
}
else {
if (!chs.empty()) {
char tmp = chs.top();
if (!match(tmp, s[i]))
return false;
chs.pop();
}
else
return false;
}
}
if (!chs.empty()) return false;
return true;
}
};
LeetCode 20. 有效的括号
最新推荐文章于 2024-04-29 10:24:20 发布