题目:20. Valid Parentheses
链接:https://leetcode.com/problems/valid-parentheses/description/
括号匹配。
python:
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack=["#"]
for i in range(len(s)):
if s[i] in ["[", "{", "("]:
stack.append(s[i])
else:
if s[i]==")":
if stack[-1]!="(":
return False
else:
stack.pop()
elif s[i]=="}":
if stack[-1]!="{":
return False
else:
stack.pop()
elif s[i]=="]":
if stack[-1]!="[":
return False
else:
stack.pop()
if len(stack)!=1:
return False
return True