[LeetCode]20. Valid Parentheses
20. Valid Parentheses
栈
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for x in s:
if x in '})]':
if not stack:
return False
if x == '}':
val = stack.pop()
if val != '{':
return False
elif x == ')':
val = stack.pop()
if val != '(':
return False
else:
val = stack.pop()
if val != '[':
return False
else:
stack.append(x)
return len(stack) == 0
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
closeB = set(')}]')
openB = {'(':')', '{':'}', '[':']'}
for c in s:
if c in closeB:
if not stack:
return False;
temp = stack.pop()
if openB[temp] != c:
return False
else:
stack.append(c)
if stack:
return False
return True

关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法