Leetcode演算法——20、判斷有效括號
阿新 • • 發佈:2018-12-15
題目
給定一個字串,只包含字元’(’, ‘)’, ‘{’, ‘}’, ‘[’ 和’]’,判斷此字串是否有效。
滿足以下條件為有效:
- 左括號必須有同樣型別的右括號相匹配
- 右括號匹配順序必須和左括號相對應
注意:一個空字串也是有效的。
Example 1: Input: “()” Output: true
Example 2: Input: “()[]{}” Output: true
Example 3: Input: “(]” Output: false
Example 4: Input: “([)]” Output: false
Example 5: Input: “{[]}” Output: true
思路
維護一個棧,每次遇到左括號便放進去,每次遇到右括號便pop一個左括號看是否與之對應。由於棧為後入先出,可以保證右括號的匹配順序和左括號相對應。
如果遍歷完字串後,棧剛好變為空,則說明字串是有效的。
python 實現
def isValid(s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
if len(s) % 2 == 1:
return False
left = {'(':')','{':'}','[' :']'}
stack = []
for char in s:
if char in left:
stack.append(char)
elif not stack or left[stack.pop()] != char:
return False
return not stack
if '__main__' == __name__:
s = "([)]"
print(isValid(s))