• 括号匹配问题


    题目

    Imagine you are building a compiler. Before running any code, the compiler must check that the parentheses in the program are balanced. Every opening bracket must have a corresponding closing bracket. We can approximate this using strings.

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
    An input string is valid if:

    • Open brackets are closed by the same type of brackets.
    • Open brackets are closed in the correct order.
    • Note that an empty string is also considered valid.

    Example:
    Input: "((()))"
    Output: True

    Input: "[()]{}"
    Output: True

    Input: "({[)]"
    Output: False

    分析

    创建一个栈。
    然后开始从左到右枚举每个字符,
    遇到左括号则进栈;
    遇到右括号,则出栈栈顶的元素。判断该元素是否和当前的右括号匹配:
    如不匹配,则返回 false.
    如匹配,则继续下一个循环;
    判断栈是否为空。为空则返回 true, 否则返回 false.

    时间复杂度为 O(n).

    代码

    class Solution:
      def isValid(self, s):
        stack = []
        matches = {
            "}": "{",
            "]": "[",
            ")": "("
        }
        for c in s:
            if c in matches.values(): # 左括号
                stack.append(c)
            elif c in matches.keys(): # 右括号
                left = stack.pop()
                if left == matches[c]:
                    continue
                else:
                    return False
            else:
                continue
        
        return len(stack) == 0
    
    
    # Test Program
    s = "()(){(())" 
    # should return False
    print(Solution().isValid(s))
    
    s = ""
    # should return True
    print(Solution().isValid(s))
    
    s = "([{}])()"
    # should return True
    print(Solution().isValid(s))
    
  • 相关阅读:
    Oracle EBS OM 发放订单
    Oracle EBS 创建 RMA
    Oracle EBS OM 保留订单
    Oracle EBS OM 删除订单行
    Oracle EBS OM 登记订单
    [转]Form中控制Tab画布不同标签间切换的方法
    [转]Form Builder:app_field.clear_dependent_fields和APP_FIELD.set_dependent_field的用法
    [整理]:oracle spool 用法
    ORA-20000:ORU-10027:buffer overflow,limit of 2000 bytes.
    [Form Builder]:CREATE_GROUP Built-in
  • 原文地址:https://www.cnblogs.com/new-start/p/11633324.html
Copyright © 2020-2023  润新知