zoukankan      html  css  js  c++  java
  • LeetCode专题-Python实现之第20题:Valid Parentheses

    导航页-LeetCode专题-Python实现

    相关代码已经上传到github:https://github.com/exploitht/leetcode-python
    文中代码为了不动官网提供的初始几行代码内容,有一些不规范的地方,比如函数名大小写问题等等;更合理的代码实现参考我的github repo

    1、读题

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

    The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

    这是经典的栈相关的题,凡是学习数据结构,一般书籍提到栈都会提及括号匹配,解析括号组成的字符串,如果是左括号就入栈,如果是右括号就出栈,看是否匹配。结束的时候再判断一发栈是否为空就行。

    2、解题

    这道题比较简单,上面读题已经讲到用栈来实现,代码逻辑很简单,如下:

    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            # 循环读取字符串s,如果是左括号则进栈,如果是有括号则出栈
            # 出栈的时候栈不能为空,循环结束的时候栈需要为空
            pars = {'(': 1, '[': 2, '{': 3, ')': -1, ']': -2, '}': -3}
            stack = list()
            for par in s:
                if pars.get(par) > 0:
                    stack.append(par)
                else:
                    if len(stack) > 0:
                        if pars.get(stack.pop()) == abs(pars.get(par)):
                            continue
                        else:
                            return False
                    else:
                        return False
            return True if len(stack) == 0 else False
    
  • 相关阅读:
    函数式宏定义与普通函数
    linux之sort用法
    HDU 4390 Number Sequence 容斥原理
    HDU 4407 Sum 容斥原理
    HDU 4059 The Boss on Mars 容斥原理
    UVA12653 Buses
    UVA 12651 Triangles
    UVA 10892
    HDU 4292 Food
    HDU 4288 Coder
  • 原文地址:https://www.cnblogs.com/cloudgeek/p/7607786.html
Copyright © 2011-2022 走看看