LeetCode--020--括号匹配

时间:2020-12-20 23:31:43

题目描述:

给定一个只包括 '('')''{''}''['']' 的字符串,判断字符串是否有效。

有效字符串需满足:

  1. 左括号必须用相同类型的右括号闭合。
  2. 左括号必须以正确的顺序闭合。

注意空字符串可被认为是有效字符串。

方法1:

  遇到左括号压入list中,遇到右括号时先判断list是否为空,是则返回false,否则弹出一个字符与其进行比较,匹配则continue 否则返回false   (32ms)

 class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
lists = []
i = 0
if len(s) == 1:
return False
elif len(s) == 0:
return True
while i < len(s):
c = s[i]
if c =='(' or c == '[' or c == '{':
# if i + 1 != len(s):
# if s[i+1] != ')' and s[i+1] != ']' and s[i+1] != '}':
# if c < s[i+1]:
# return False
#([])这种竟然算对,好吧
lists.append(c) elif c == ')': if len(lists) != 0:
t = lists.pop()
if t == '(':
i+=1
continue
else:
return False
else:
return False
elif c == ']': if len(lists) != 0:
t = lists.pop()
if t == '[':
i+=1
continue
else:
return False
else:
return False
elif c == '}': if len(lists) != 0:
t = lists.pop()
if t == '{':
i+=1
continue
else:
return False
else:
return False
i += 1 if len(lists) != 0:
return False
else:
return True

简洁版:(28ms)

 class Solution:
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for c in s:
if c == '(' or c == '{' or c == '[':
stack.append(c)
elif not stack:
return False
elif c == ')' and stack.pop() != '(':
return False
elif c == '}' and stack.pop() != '{':
return False
elif c == ']' and stack.pop() != '[':
return False
return not stack

利用字典:(24ms)

 class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
pars = [None]
parmap = {')': '(', '}': '{', ']': '['}
for c in s:
if c in parmap:
if parmap[c] != pars.pop():
return False
else:
pars.append(c)
return len(pars) == 1

时间最短:(20ms)

  用抛出异常的方式把类似)()剔除

 class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
try:
stack = []
for key in s :
if(key == '(' or key == '[' or key == '{'):
stack.append(key)
else:
if((key == ')' and stack.pop() == '(') or
(key == ']' and stack.pop() == '[') or
(key == '}' and stack.pop() == '{')):
pass
else:
return False
if(len(stack) == 0):
return True
except IndexError:
return False
return False

2018-07-22 18:48:45