有效字符串需滿足:
1、左括號必須用相同類型的右括號閉合。
2、左括號必須以正確的順序閉合。
3、注意空字符串可被認為是有效字符串。
示例一:
輸入:s = "()"
輸出:true
示例二:
輸入:s = "()[]{}"
輸出:true
示例三:
輸入:s = '([{}])'
輸出:true
示例四:
輸入:s = '{(}'
輸出:false
方法一:字符串
class Solution:
def isValid(self, s: str) -> bool:
if not isinstance(s, str): # 是否是字符串對象
return False
if not s: # 為空返回True
return True
if len(s) % 2 != 0: # 取余不為0,則代表字符串長度為基數,直接返回False
return False
while '()' in s or '[]' in s or '{}' in s:
s = s.replace('()', '').replace('[]', '').replace('{}', '') # 刪除字符串中的'()'、'[]'、'{}'
return s == '' # 判斷s是否為空
方法二:棧
class Solution:
def isValid(self, s: str) -> bool:
if not isinstance(s, str): # 是否是字符串對象
return False
if not s: # 為空返回True
return True
if len(s) % 2 != 0: # 取余不為0,則代表字符串長度為基數,直接返回False
return False
dic = {'(': ')', '[': ']', '{': '}'}
check = []
for i in s:
if i in dic.keys(): # 循環判斷字符串列表s中的元素是否為左括號
check.append(i) # 元素放入列表
else:
if not check: # 表明不存在左括號,但存在右括號,返回False
return False
elif dic[check[-1]] == i: # 彈出check列表中最后一個元素,作為dic字典key,檢測是否與值對應
check.pop() # 對應即彈出check的最后一個元素
else: # 不對應則不是有效字符,跳出循環
break
return check == []