LeetCode-20:有效括号(Valid Parentheses)

题目链接:

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.

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

方法一

用栈(先进后出FILO)来操作,将所有的字符依次入栈,当栈顶的括号和正要入栈的括号匹配时将栈顶的括号弹出且不入栈,否则入栈新的括号。最后,只有当栈里没有括号时,才表明输入是有效的。(技巧:python中的列表可以模拟数据结构中的栈操作,使用列表中的append()和pop()方法

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

猜你喜欢

转载自blog.csdn.net/qq_36653505/article/details/82192630