美文网首页
Valid Parentheses 括号开闭

Valid Parentheses 括号开闭

作者: 穿越那片海 | 来源:发表于2017-03-05 18:14 被阅读0次

Easy, Dynamic Programming

Question

给定string只含 '(', ')', '{', '}', '[', ']',判断string是否valid

Example: "()[]{}": true
"([)]" : false

Solution

论坛一个coder的方法,做减法,把配对的括号一一去除。想法非常简单,缺点是complexity会比较高。

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) % 2 != 0:
            return False
        while "()" in s or "[]" in s or "{}" in s:
            s = s.replace("()","").replace("[]","").replace("{}","")
        return s == ''

更加有效的方法是利用堆栈。

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        dic = {'(':')','{':'}','[':']'}
        stack = []
        for c in s:
            if c in dic:
                stack.append(c)
            elif stack == [] or dic[stack.pop()] != c:
                return False
        return stack == []

相关文章

网友评论

      本文标题:Valid Parentheses 括号开闭

      本文链接:https://www.haomeiwen.com/subject/ahsegttx.html