暴力替换 时间复杂度 O(N^2)
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 == 1:
return False
while True:
startLen = len(s)
s = s.replace('[]','')
s = s.replace('{}','')
s = s.replace('()','')
if len(s) == startLen:
return s == ''
利用栈 时间复杂度 O(N)
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 == 1:
return False
dic = {'(':')', '[':']', '{':'}', '?':'?'}
stack = ['?']
for char in s:
if char in dic:
stack.append(char)
elif dic[stack.pop()] != char:
return False
return len(stack) == 1