관리 메뉴

솜씨좋은장씨

[leetCode] 20. Valid Parentheses (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 20. Valid Parentheses (Python)

솜씨좋은장씨 2020. 6. 17. 18:41
728x90
반응형

Given a string 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.

Note that an empty string is also considered valid.

 

Example 1:

Input: "()"
Output: true

Example 2:

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

Example 3:

Input: "(]"
Output: false

Example 4:

Input: "([)]"
Output: false

Example 5:

Input: "{[]}"
Output: true

Solution

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

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

 

Comments