【LEETCODE】20-Valid Parentheses

1278 ワード

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