Leetcode

20. Valid Parentheses

2016-08-03  本文已影响20人  oo上海

20. Valid Parentheses

题目:

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

难度:

Easy

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

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

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

需要检查几件事:

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 == []
上一篇 下一篇

猜你喜欢

热点阅读