給定一個只包括 '(',')','{','}','[',']' 的字符串,判斷字符串是否有效。
有效字符串需滿足:
左括號必須用相同類型的右括號閉合。
左括號必須以正確的順序閉合。
注意空字符串可被認爲是有效字符串。
示例 1:
輸入: "()"
輸出: true
示例 2:
輸入: "()[]{}"
輸出: true
示例 3:
輸入: "(]"
輸出: false
示例 4:
輸入: "([)]"
輸出: false
示例 5:
輸入: "{[]}"
輸出: true
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/valid-parentheses
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
class Solution:
def isValid(self, s: str) -> bool:
zhan=[]
n=len(s)
for i in range(n):
if s[i] in [')',']','}']:
#遇到右括號出棧並 判斷
if (zhan):
temp=zhan.pop()#出棧
if (temp is '(' and s[i] is ')') or (temp is '[' and s[i] is ']') or (temp is '{' and s[i] is '}'):
continue
else:
#匹配失敗
return False
else:
#空了,沒有可以匹配的
return False
else:
#遇到左括號入棧
zhan.append(s[i])
if not zhan:
return True
else:
return False