• LeetCode小白菜笔记[6]:Valid Parentheses


    LeetCode小白菜笔记[6]:Valid Parentheses

    20. Valid Parentheses [Easy]

    题目: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.

    题目是判别一个表达式是不是有效的,实际上就是看左右括号是不是符合嵌套规范并且一一对应。这道题目比较简单,记忆中应该是数据结构与算法课上用来解释的应用的一个例子。每检测到一个左括号,就将其压栈,每遇到一个右括号,先判断栈是否为空,如果空直接 False (说明右括号多了),否则再看如果与栈顶的可以对应,那么就pop出栈顶元素;如果不对应直接 return False。这样检查完所有的括号后,如果栈空了,说明是valid,否则返回 False。

    代码如下:

    class Solution(object):
        def isValid(self, s):
            """
            :type s: str
            :rtype: bool
            """
            paren = {'(': 1, '{' : 2, '[' : 3, ')': -1, '}' : -2, ']' : -3}
            stack = []
            for i in range(len(s)):
                if paren.has_key(s[i]):
                    if paren[s[i]] > 0 :
                        stack.append(paren[s[i]])
                    else:
                        if len(stack) == 0:
                            return False
                        elif paren[s[i]] + stack[-1] == 0:
                            stack.pop()
                        else:
                            return False
            if len(stack) == 0:
                return True
            else:
                return False

    ( 愚蠢的我又又又又把 str 这个关键字忘了直接当变量名了。。。)修改过后结果如下:

    这里写图片描述

    又又又又是勉强通过。。。看了下discuss上的code,如下:

    class Solution:
        # @return a boolean
        def isValid(self, s):
            stack = []
            dict = {"]":"[", "}":"{", ")":"("}
            for char in s:
                if char in dict.values():
                    stack.append(char)
                elif char in dict.keys():
                    if stack == [] or dict[char] != stack.pop():
                        return False
                else:
                    return False
            return stack == []                    

    runtime快了一些,但是也只是百分之39点多。不过code写法上明显比较好。

    总结 :

    1. str是个Python关键字,不要再用作变量名了 - . - b
    2. list元素遍历如果用不到下标的话可以直接 for value in list ,然后 value +=1 这样,而不必 for i in range(len(list)),再 list[i] += 1。
    3. 示例代码中的dict直接将匹配的字符作为键值对,更加方便。
    4. 直接pop出来比较即可,如果不等于直接 False 不影响结果,如果等于则需要pop,这样就省去一次取值的时间。
    5. 像返回boolean这种可以直接 return 判断表达式,不要用 if 语句,显得好笨TAT。

    THE END

    2017/12/25 Fri 19:20

  • 相关阅读:
    Attributes in C#
    asp.net C# 时间格式大全
    UVA 10518 How Many Calls?
    UVA 10303 How Many Trees?
    UVA 991 Safe Salutations
    UVA 10862 Connect the Cable Wires
    UVA 10417 Gift Exchanging
    UVA 10229 Modular Fibonacci
    UVA 10079 Pizza Cutting
    UVA 10334 Ray Through Glasses
  • 原文地址:https://www.cnblogs.com/morikokyuro/p/13256850.html
Copyright © 2020-2023  润新知