[勇者闖LeetCode] 20. 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.
Information
- Tags: Stack | String
- Difficulty: Easy
Solution
用棧存儲需要遇到的右括號。掃描字符串時遇到左括號則其對應的右括號入棧,遇到右括號則出棧並判斷兩個右括號是否相同,若不相同則返回false
。掃描結束後,若棧內還有元素,則返回false
。
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
l = {"(": ")", "[": "]", "{": "}"}
ans = []
for x in s:
if x in l:
ans.append(l[x])
elif (len(ans) == 0 or ans.pop() != x):
return False
return False if len(ans) > 0 else True