zoukankan      html  css  js  c++  java
  • 有效的括号

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

    有效字符串需满足:

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

    示例 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
    
    
  • 相关阅读:
    h5 . css入门 2.CSS基础
    html5与css 1. web标准及组成
    SQL编程
    JMeter学习(八)JDBC测试计划-连接Oracle
    JMeter学习(七)聚合报告之 90% Line 正确理解
    JMeter学习(六)集合点
    JMeter学习(五)检查点
    JMeter学习(十四)jmeter_断言使用
    JMeter学习(四)参数化
    JMeter学习(三)元件的作用域与执行顺序
  • 原文地址:https://www.cnblogs.com/CCCrunner/p/11781571.html
Copyright © 2011-2022 走看看