• 有效的括号


    给定一个只包括'(',')','{','}','[',']'的字符串,判断字符串是否有效。

    有效字符串需满足:

    左括号必须用相同类型的右括号闭合。
    左括号必须以正确的顺序闭合。
    注意空字符串可被认为是有效字符串。

    示例 1:
    
    输入: "()"
    输出: true
    示例 2:
    
    输入: "()[]{}"
    输出: true
    示例 3:
    
    输入: "(]"
    输出: false
    示例 4:
    
    输入: "([)]"
    输出: false
    示例 5:
    
    输入: "{[]}"
    输出: true
    
    
    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
                    top_element = stack.pop() if stack else '#'
                    # 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
    
    
  • 相关阅读:
    ASP输出成n列的表格形式显示的方法,多行多列
    1003
    1005
    Linq to sql 迭代器bug?
    通过global.asax向所有文件注册js
    asp.net任务调度之Quartz.net
    SQL Server 批量插入数据的两种方法
    C#通过反射实例化对象
    linq to sql 学习
    C#全角和半角转换
  • 原文地址:https://www.cnblogs.com/CCCrunner/p/11781571.html
Copyright © 2020-2023  润新知