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

    题目要求

    给定一个字符串所表示的括号序列,包含以下字符: '(', ')''{''}''[' and ']', 判定是否是有效的括号序列。

    样例

    括号必须依照 "()" 顺序表示, "()[]{}" 是有效的括号,但 "([)]"则是无效的括号。

    分析

    栈的简单应用,遍历字符串,遇到左括号push,遇到右括号就pop判断匹配,这里利用python的字典来方便匹配。还需要考虑到字符串已经遍历完但是栈里面元素是否有无的情况。用python写注意缩进,第一次直接在lintcode网站上写没有按照PEP8规范,搞得我WA了半天,后来直接拖出去sublime写再复制回去就好了。

    class Solution:
        """
        @param: s: A string
        @return: whether the string is a valid parentheses
        """
        def isValidParentheses(self, s):
            # write your code here
            stack = []
            book = {
                '}': '{',
                ']': '[',
                ')': '(',
            }
            list = ['(', '{', '[']
            for i in s:
                if i in list:
                    stack.append(i)
                else:
                    if len(stack) == 0:
                        return False
                    p = stack.pop()
                    if p != book[i]:
                        return False
            if len(stack) == 0:
                return True
            else:
                return False
            
  • 相关阅读:
    A visual proof that neural nets can compute any function 2
    Matrix
    Formula
    ID and CLASS
    hugeng007_diary01_the living way
    the mathematical knowledge
    sys.argv[]
    The Convolutional Networks
    DVWA之XSS (跨站脚本攻击)存储型+反射型。
    DVWA之 File Inclusion 文件包含
  • 原文地址:https://www.cnblogs.com/liangjiahao713/p/7739240.html
Copyright © 2011-2022 走看看