20. Valid Parentheses Python3

Yelim Kim·2021년 10월 1일
0

Python Algorithm Interview

목록 보기
20/36
post-thumbnail

Problem

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.

Example 1:

Input: s = "()"
Output: true

Example 2:

Input: s = "()[]{}"
Output: true

Example 3:

Input: s = "(]"
Output: false

Example 4:

Input: s = "([)]"
Output: false

Example 5:

Input: s = "{[]}"
Output: true

Constraints:

1 <= s.length <= 104
s consists of parentheses only '()[]{}'.

My code

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        stack.append(0)
        if ((s[0] ==")") or (s[0] == "}") or (s[0] == "]")):
            return False
        for i in s:
            if ((i =="(") or (i == "{") or (i == "[")):
                stack.append(i)
            if ((i ==")") or (i == "}") or (i == "]")):
                tem = stack[-1]
                if tem == 0:
                    return False
                if tem == "(" and i!=")":
                    break
                if tem == "{" and i!="}":
                    break
                if tem == "[" and i!="]":
                    break
                else:
                    stack.pop()
        if len(stack) == 1:
            return True
        if len(stack) == 0:
            return False

Review

[실행 결과]
Runtime: 24 ms Memory Usage: 14.1 MB

[접근법]
처음부터 ) 나 }나 ]가 나오는 예외 해결
(나 {나 [의 짝궁을 맞춰서 짝궁이 나오면 stack에서 제거, 짝궁이 안나오면 그대로 남겨둠
제거할거 제거하고 남길거 남긴 후 마지막에 남은 stack의 길이가 1(처음에 있던 0)이면 True 아니면 False 출력한다

[느낀점]
옛날에 비슷한 문제를 풀었던 적이 있어서 블로그가서 코드를 봤는데 그 당시에 해결하지 못하고 남겨뒀던 문제였다... 다시 코드를 확인하고 생각해보니까 금방 해결됐음 ... 나... 그래도 실력이 늘은 걸까....? ㅠㅠ:웃으며눈물을흘리는_얼굴:

profile
뜬금없지만 세계여행이 꿈입니다.

0개의 댓글