zoukankan      html  css  js  c++  java
  • 括号匹配问题

    题目

    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))
    
  • 相关阅读:
    搭建高可用mongodb集群—— 副本集
    搭建高可用mongodb集群(一)——mongodb配置主从模式
    单线程异步回调机制的缺陷与node的解决方案
    js实现接口的几种方式
    访问者模式和php实现
    策略模式和php实现
    状态模式和php实现
    观察者模式和php实现
    C语言之一般树
    电子相册之bitmap
  • 原文地址:https://www.cnblogs.com/new-start/p/11633324.html
Copyright © 2011-2022 走看看