본문 바로가기
Coding Test

[CT] Leet Code 20. Valid Parentheses python3 ver.

by Luciditas 2023. 9. 28.
728x90

20. Valid Parentheses

Solved

 

Easy

 

Topics

 

Companies

 

Hint

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

 

Example 1:

Input: s = "()"

Output: true

 

Example 2:

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

Output: true

 

Example 3:

Input: s = "(]"

Output: false

 

Constraints:

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

Accepted

3.8M

 

Submissions

9.5M

 

Acceptance Rate

40.2%

 

나의 풀이

class Solution:
    def isValid(self, s: str) -> bool:
        list_s = list(s)
        # String s를 list화 한다.
        answer = True
        stack = []
        for i in list_s:
            # list_s를 돌면서
            if i == '(' or i =='[' or i =='{':
                # i가 '('거나 '['거나 '{'라면
                stack.append(i)
                # stack에 전부 append한다.
            elif len(stack) != 0:
                # stack에 요소가 남아 있을 때
                if (i == ']' and stack[-1] == '[') or (i == ')' and stack[-1] == '(') or (i == '}' and stack[-1] == '{'):
                    # 위의 조건을 만족한다면
                    stack.pop()
                    # stack에서 pop해준다.
                else :
                    # stack에 남아 있는 요소가 없다면
                    answer = False
                    # answer는 False다.
                    break
                    # 반복문 탈출
            else :
                # if i == '(' or i =='[' or i =='{'의 조건을 만족하지 않는다면
                answer = False
                # answer는 False다.
                break
                # 반복문 탈출

        if len(stack) != 0:
            # 만약 반복문을 전부 돌고 나서도 stack에 요소가 남아 있다면            
            answer = False
            # answer는 False가 된다.
        return answer
728x90