题目链接
https://leetcode.cn/problems/valid-parentheses/
代码
仅使用栈
class Solution:
def isValid(self, s: str) -> bool:
stack = []
for i in s:
if i == '(':
stack.append(')')
elif i == '{':
stack.append('}')
elif i == '[':
stack.append(']')
elif not stack or stack[-1] != i:
return False
elif stack.pop() != i:
return False
return True if len(stack) == 0 else False
字典
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {
'(': ')',
'[': ']',
'{': '}'
}
for item in s:
if item in mapping.keys():
stack.append(mapping[item])
elif not stack or stack[-1] != item:
return False
else:
stack.pop()
return True if not stack else False