[leetcode] 20. Valid Parentheses

Joy·2022년 10월 13일
0

Coding Test

목록 보기
48/48

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = ""
        for bracket in s:
            if bracket == "[" :
                stack += "a"
            elif bracket =="{":
                stack += "b"
            elif bracket == "(":
                stack += "c"
            else:
                if stack == "":
                    return False
                else: 
                    if bracket == "]" :
                        if stack[-1]=="a":
                            stack = stack[:-1]
                        else : return False
                    elif bracket =="}":
                        if stack[-1] == "b":
                            stack = stack[:-1]
                        else : return False

                    else :
                        if stack[-1] == "c":
                            stack = stack[:-1]
                        else : return False
        if stack == "":
            return True
        else : return False

instead of repeating if - else, could use map and list stack

class Solution:
    def isValid(self, s: str) -> bool:
        Map = {")": "(", "]": "[", "}": "{"}
        stack = []

        for c in s:
            if c not in Map:
                stack.append(c)
                continue
            if not stack or stack[-1] != Map[c]:
                return False
            stack.pop()

        return not stack
profile
roundy

0개의 댓글