0
点赞
收藏
分享

微信扫一扫

LeetCode 20: 有效的括号

沉浸在自己的世界里 2023-02-03 阅读 98


​​https://leetcode-cn.com/problems/valid-parentheses/solution/you-xiao-de-gua-hao-by-leetcode/​​

class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""

# The stack to keep track of opening brackets.
stack = []

# Hash map for keeping track of mappings. This keeps the code very clean.
# Also makes adding more types of parenthesis easier
mapping = {")": "(", "}": "{", "]": "["}

# For every bracket in the expression.
for char in s:

# If the character is an closing bracket
if char in mapping:

# Pop the topmost element from the stack, if it is non empty
# Otherwise assign a dummy value of '#' to the top_element variable
if stack:
top_element = stack.pop()
else:
top_element = '#'

# The mapping for the opening bracket in our hash and the top
# element of the stack don't match, return False
if mapping[char] != top_element:
return False
else:
# We have an opening bracket, simply push it onto the stack.
stack.append(char)

# In the end, if the stack is empty, then we have a valid expression.
# The stack won't be empty for cases like ((()
return not stack


solu = Solution()
succuss = solu.isValid(')()]')
print(succuss)

 

举报

相关推荐

0 条评论