原题链接:https://leetcode.com/problems/valid-parentheses/
Description
Given a string containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
括号匹配。。
class Solution {
public:
bool isValid(string s) {
stack<char> A;
size_t n = s.length();
for (size_t i = 0; i < n; i++) {
char &ch = s[i];
if (ch == '(' || ch == '{' || ch == '[') {
A.push(ch);
continue;
}
if (ch == ')') {
if (!A.size()) return false;
if (A.top() == '(') A.pop();
else A.push(ch);
}
if (ch == '}') {
if (!A.size()) return false;
if (A.top() == '{') A.pop();
else A.push(ch);
}
if (ch == ']') {
if (!A.size()) return false;
if (A.top() == '[') A.pop();
else A.push(ch);
}
}
return !A.size();
}
};