【LEETCODE】20-Valid Parentheses

来源:互联网 发布:java杨辉三角几年里 编辑:程序博客网 时间:2024/06/15 11:28

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.


思路:


遇到左括号,入栈

遇到了右括号,如果此时栈顶元素是相应的左括号,则True,其他情况为False

遇到一对后,弹出

[ (  ) ]

( )  [ ]  { }


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


0 0