zoukankan      html  css  js  c++  java
  • 20. Valid Parentheses

    20. Valid Parentheses

    1. 题目

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

    An input string is valid if:

    1. Open brackets must be closed by the same type of brackets.
    2. Open brackets must be closed in the correct order.

    Note that an empty string is also considered valid.

    Example 1:

    Input: "()"
    Output: true
    

    Example 2:

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

    Example 3:

    Input: "(]"
    Output: false
    

    Example 4:

    Input: "([)]"
    Output: false
    

    Example 5:

    Input: "{[]}"
    Output: true
    

    2. 思路

    本题是验证给定的字符串,是不是有效的括号串。思路也很简单,可以用栈的方式实现。如果遇到了"[" ,"{" ,"("就入栈。如果遇到了"]" ,"}" ,")" 就出栈前一个字符,看前一个字符是否能匹配当前的字符。如果不行,则当前字符也入栈。最后程序结束的时候判断栈里面还有多少元素,如果是0则代表字符串是有效的括号串。

    3. 实现

    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            stack = []
            if len(s) == 0 : return True
    
            for e in s :
                if len(stack) == 0 :
                    stack.append(e)
                    continue
                t = stack[-1]
                if ( t == "(" and e == ")" ) or ( t == "{" and e == "}" ) or ( t == "[" and e == "]" ):
                    stack.pop(-1)
                else:
                    stack.append(e)
            if len(stack) == 0 :return True
            return False
    
  • 相关阅读:
    如何管理自己的文件夹
    Mybatis 笔记
    Try Catch Finally
    Java JDK安装小谈
    android 相关学习笔记
    nodejs 复制目录,调用cmd命令
    ajax图片上传,基于firefox
    一切皆命令
    javascript 之牛人感悟,必看学习
    jQuery中添加自定义或函数方法
  • 原文地址:https://www.cnblogs.com/bush2582/p/10927158.html
Copyright © 2011-2022 走看看