LeetCode#20. Valid Parentheses
2017-11-06 本文已影响4人
夹小欣
今天是两道easy难度的题,印象中是当初学数据结构时候讲过的栗子。
括号匹配,用栈来处理,需要注意一下越界问题,
class Solution(object):
def isValid(self, s):
stack_left = []
if len(s) <= 1:
return False
for char in s:
n = len(stack_left)
#这个地方用or和用多个elif 的运行时间差距很大,判断机制的引入不是没道理
if char == '(' or char =='{' or char =='[':
stack_left.append(char)
continue
if n>0:
if char ==')' :
if stack_left[-1]=='(':
stack_left.pop()
else:
return False
elif char =='}' :
if stack_left[-1]=='{':
stack_left.pop()
else:
return False
elif char ==']' :
if stack_left[-1]=='[':
stack_left.pop()
else:
return False
else:
return False
if len(stack_left) == 0:
return True
else:
return False
```