from typing import List
#--------input---------
s = ['{[([])]}']
s1 = '[)'
s2 = '()'
s3 = ']'
#----------------------------fail--------------------------------
#--fail1:[)不能过...
# def isVld(s: str) -> bool:
# ram = []
# for x in s:
# if x == '{' or x == '[' or x == '(':
# ram.append(x)
# else:
# ram.pop()
# if ram:
# return(False)
# else:
# return(True)
#--fail2:]不能过,ram为空时[-1]越界
# def isVld(s: str) -> bool:
# ram = []
# for x in s:
# print(x,'\n')
# if x == '{' or x == '[' or x == '(':
# ram.append(x)
# elif x == '}' and ram[-1] == '{' :
# ram.pop()
# elif x == ']' and ram[-1] == '[' :
# ram.pop()
# elif x == ')' and ram[-1] == '(' :
# ram.pop()
# else:
# return(False)
# if ram:
# return(False)
# else:
# return(True)
#----------------------------success--------------------------------
#----try1: 执行用时:36 ms,内存消耗:13.6 MB,代码看上去很笨,不影响实用
# def isVld(s: str) -> bool:
# ram = []
# for x in s:
# if x == '{' or x == '[' or x == '(':
# ram.append(x)
# else:
# if(len(ram)>0):
# if x == '}' and ram[-1] == '{' : #字符串也可用[-1]表示最后一个字符,注意字符串为空时会报错
# ram.pop()
# elif x == ']' and ram[-1] == '[' :
# ram.pop()
# elif x == ')' and ram[-1] == '(' :
# ram.pop()
# else:
# return(False)
# else:
# return(False)
# if ram:
# return(False)
# else:
# return(True)
#----try2: 执行用时:36 ms,内存消耗:13.7 MB,代码看上去有点笨,不影响实用
# def isVld(s: str) -> bool:
# if not s:
# return True
# ram = []
# for x in s:
# if x == '{' or x == '[' or x == '(':
# ram.append(x)
# else:
# if ram:
# if x == '}' and ram.pop() != '{' :
# return False
# elif x == ']' and ram.pop() != '[' :
# return False
# elif x == ')' and ram.pop() != '(' :
# return False
# else:
# return False
# if ram:
# return False
# else:
# return True
#----try best: 执行用时:40 ms,内存消耗:13.7 MB,代码看上去最简洁,同时加入如果为奇数个符号直接返回False
#时间复杂度 O(N)
#空间复杂度 O(N)
def isVld(s: str) -> bool:
if not s: #判断字符串、数组是否为空,可以直接用这种方式,不必用len(s)==0
return True
if len(s)%2 == 1: #如果为奇数个符号直接返回False
return False
ram = []
for x in s:
if x == '{':
ram.append('}')
elif x == '[':
ram.append(']')
elif x == '(':
ram.append(')')
elif not ram or x != ram.pop():
return False
if ram:
return False
else:
return True
#--------output---------
print(isVld(s))
print(isVld(s1))
print(isVld(s2))
print(isVld(s3))