[leetcode] 20. Valid Parentheses

2021. 8. 10. 15:56노트/Algorithm : 알고리즘

 

20. Valid Parentheses

 

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.

 

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

 

class Solution:
    def isValid(self, s: str) -> bool:
        char_dict = {'(':')', '{':'}','[':']'}
        l = [] 
  
        for st in s: 
            if st in ['(','{','[']:
                l.append(st) 
            elif st in [')','}',']']:
                # l 이 빈 리스트라면
                if not l: 
                    return False
                
                # l 꺼냈는데, 괄호 매칭 안된다면 
                if st != char_dict[l.pop()]:  
                    return False
                
                # 괄호 매칭 됐으면 다음글자 보자
                else:
                    continue
                    
        # l에 글자 추가만 되있다면
        if len(l) != 0:
            return False
        
        return True