跳到主要内容

Valid Parentheses

描述

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.

分析

代码

# Valid Parentheses
# Time complexity O(n), Space complexity O(n)
class Solution:
def isValid(self, s: str) -> bool:
left = "([{"
right = ")]}"
stk = []

for c in s:
if c in left:
stk.append(c)
else:
if stk and stk[-1] == left[right.index(c)]:
stk.pop()
else:
return False
return len(stk) == 0

相关题目