[LeetCode] Valid Parentheses

동스토리 ㅣ 2021. 8. 12. 13:25

반응형

안녕하세요.

 

LeetCode 20번 Valid Parentheses 문제 풀이 하겠습니다.

 

https://leetcode.com/problems/valid-parentheses/

 

Valid Parentheses - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

[문제]


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.

 

[TestCase]

 

 

[해설]

 

스택을 사용한 문제풀이

1. 리스트를 만든다.

2. '(', '{', '[' 는 stack에 추가한다.

3. stack에 길이가 0인 경우, 괄호 짝 이 안맞을 경우 False를 리턴한다.

4. 최종 stack에 길이가 0이 아닐경우 False를 리턴한다.

5. 그 외 True 리턴한다.

 

[코드]

 

class Solution:
    def isValid(self, s: str) -> bool:
        
        s_list = list(s)
        stack = []
        result = True

        for s in s_list:
            if s == '(' or s =='{' or s == '[':
                stack.append(s)
            else:
                if len(stack) ==0:
                    result = False
                elif s ==')':
                    if stack.pop() != '(':
                        result = False
                elif s =='}':
                    if stack.pop() != '{':
                        result = False
                elif s ==']':
                    if stack.pop() != '[':
                        result = False
        
        if len(stack) !=0:
            result = False

        return result

 

 

감사합니다.

반응형