Valid Parentheses
// Runtime 0ms (Beats 100%)
// Memory 6.3 MB (Beats 94.2%)
class Solution {
public:
bool isValid(string s) {
stack<char> seen;
for (const auto ch : s) {
if (ch == '(' || ch == '{' || ch == '[') {
seen.emplace(ch);
continue;
}
if (ch == ')') {
if (seen.size() <= 0 || seen.top() != '(') {
return false;
}
seen.pop();
}
else if (ch == '}') {
if (seen.size() <= 0 || seen.top() != '{') {
return false;
}
seen.pop();
}
else if (ch == ']') {
if (seen.size() <= 0 || seen.top() != '[') {
return false;
}
seen.pop();
} else {
continue;
}
}
return seen.size() == 0;
}
};# Runtime: 34ms (Beats 83%)
# Memory: 16.37 MB (Beats 30%)
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for c in s:
if c in ['(', '{', '[']:
stack.append(c)
continue
elif c == ')':
if not len(stack):
return False
top = stack[-1]
if top != '(':
return False
elif c == '}':
if not len(stack):
return False
top = stack[-1]
if top != '{':
return False
elif c == ']':
if not len(stack):
return False
top = stack[-1]
if top != '[':
return False
else:
continue
stack.pop()
return len(stack) == 0