原題:給定一個只包括 '(',')','{','}','[',']' 的字符串,判斷字符串是否有效。
有效字符串需滿足:
左括號必須用相同類型的右括號閉合。
左括號必須以正確的順序閉合。
注意空字符串可被認爲是有效字符串。
解法一:(棧)
如果此時我們遍歷的字符是括號的左半部分,那麼將字符入棧,如果棧頂元素和此時遍歷的元素正好組合成一個括號,則出棧。
最後如果棧爲空則返回True,反之,返回False。
寫法一:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
ans = []
if s =="":
return True
for i in range(0,len(s)):
if ans != []:
if ans[-1] == '(' and s[i] == ")":
ans.pop()
continue
elif ans[-1] == '{' and s[i] == "}":
ans.pop()
continue
elif ans[-1] == '[' and s[i] == "]":
ans.pop()
continue
ans.append(s[i])
if ans == []:
return True
else:
return False
寫法二:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
ans = []
mapping ={")":"(","}":"{","]":"["} #創建字典
for char in s:
if char in mapping:
top_element = ans.pop() if stack else '#'
if mapping[char] != top_element:
return False
return not ans