題目描述:
給定一個字符串所表示的括號序列,包含以下字符: '(', ')', '{', '}', '[' and ']', 判定是否是有效的括號序列。
樣例
括號必須依照 "()" 順序表示, "()[]{}" 是有效的括號,但 "([)]"則是無效的括號。
題目分析:
循環字符串,遇左括號入棧。
遇右括號,從棧頂取元素然后配對,判斷配對結果。
最后再判斷棧是否不為空。
源碼:
class Solution:
# @param {string} s A string
# @return {boolean} whether the string is a valid parentheses
def isValidParentheses(self, s):
# Write your code here
if s is None: return False
x = ['[','(','{']
y = ["]",")","}"]
z = ["()","[]","{}"]
res = []
for i in s:
if i in x:
res.append(i) # 入棧
elif i in y:
# 如果收到一個右括號,但是res中無左括號,直接返回False
if res == []:
return False
else:
temp = res.pop(-1) + i
# 其余情況,出棧一個左括號,判斷左括號+右括號是否有效
if temp not in z:
return False
# 如果所有括號對都滿足,但是res還有左括號,返回False
if len(res) != 0:
return False
return True
