TIL #108 : [Algorithm] LeetCode 20. Valid Parentheses

셀레스틴 허·2021년 3월 25일
0

ALGORITHM

목록 보기
14/18
post-thumbnail
post-custom-banner

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

Constraints

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

풀이 코드:

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        if len(s) % 2 != 0:
            return False
            
        elif len(s) == 0:
            return False
        
        stack = []

        parameters = {")": "(", "}": "{", "]": "["}

        for string in s:
            if string in parameters:
                if stack:
                    stack_pop = stack.pop()
                
                if parameters[string] != stack_pop:
                    return False
                
            else:
                stack.append(string)

        return True

Wrong Answer... 처음부터 다시 차근차근...

class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """
        stack = []

        lookup = {")": "(", "}": "{", "]": "["}

        for p in s:
            if p in lookup.values():
            	stack.append(p)
            elif stack and lookup[p] == stack[-1]:
            	stack.pop()
            else:
            	return False
                
        return stack == []

코드 출처 ㅣ Timothy Chang의 영상

반성하자. 딕셔너리를 쓰고 왜 활용을 안하니...

profile
Software Developer / 고통은 필연, 괴로움은 선택
post-custom-banner

0개의 댓글