20. Valid Parentheses [easy] (Python)

题目链接

https://leetcode.com/problems/valid-parentheses/

题目原文

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.

题目翻译

给定一个字符串,只包含 '(', ')', '{', '}', '['']' 这几个字符,判断输入字符串是否是有效的。
所有的括号必须以正确的顺序闭合,比如 "()""()[]{}" 是有效的,但 "(]""([)]" 是无效的。

思路方法

思路一

用栈来操作,将所有的字符依次入栈,当栈顶的括号和正要入栈的括号匹配时将栈顶的括号弹出且不入栈,否则入栈新的括号。最后,只有当栈里没有括号时,才表明输入是有效的。

代码

class Solution(object):
    def isValid(self, s):
        """ :type s: str :rtype: bool """
        pars = [None]
        parmap = {')': '(', '}': '{', ']': '['}
        for c in s:
            if c in parmap and parmap[c] == pars[len(pars)-1]:
                pars.pop()
            else:
                pars.append(c)
        return len(pars) == 1

思路二

实际上,通过观察可以发现:如果正要入栈的是右括号,而栈顶元素不是能与之消去的相应左括号,那么该输入字符串一定是无效的。于是,可以大的加快判断过程。

代码

class Solution(object):
    def isValid(self, s):
        """ :type s: str :rtype: bool """
        pars = [None]
        parmap = {')': '(', '}': '{', ']': '['}
        for c in s:
            if c in parmap:
                if parmap[c] != pars.pop():
                    return False
            else:
                pars.append(c)
        return len(pars) == 1

说明
当然这里使用dict来存放括号的匹配关系不是必要的,直接通过字符之间ascii码的差值判断也是比较快的。

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51697963

    原文作者:coder_orz
    原文地址: https://blog.csdn.net/coder_orz/article/details/51697963
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞