20. Valid Parentheses

20. Valid Parentheses

题目:

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

难度:

Easy

虽然知道肯定是用stack来解决,但是我是看了hint才自己解答的,因为可能想复杂了。

因为一共只有三种状况"(" -> ")", "[" -> "]", "{" -> "}".

一遇到左括号就入栈,右括号出栈,这样来寻找对应

需要检查几件事:

  • 右括号时stack里还有没有东西
  • 出stack的是否对应
  • 最终stack是否为空
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        leftP = "([{"
        rightP = ")]}"
        
        stack = []
        for char in s:
            if char in leftP:
                stack.append(char)
            elif char in rightP:
                if stack == []:
                    return False
                item = stack.pop()
                if char == "]" and item != "[":
                    return False
                elif char == ")" and item != "(":
                    return False
                elif char == "}" and item != "{":
                    return False
        return stack == []
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容