📊알고리즘, 문제풀이/📈문제풀이 (PS)

[알고리즘][Python] LeetCode 20 Valid Parentheses 문제 풀이

Written by Donghak Park

문제 출처 : 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


문제 해석 : 괄호가 제대로 구성되어 있는지 검사하는 문제이다.

 

문제 풀이 : 시작 괄호와 끝 괄호의 짝을 매칭해가면서 검사하면 된다.


풀이 코드

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        a = {
            ')': '(',
            ']': '[',
            '}': '{'
        }
        s = list(s)
        while s:
            temp = s.pop(0)
            if stack and (temp in a.keys()):
                if a[temp] == stack[-1]:
                    stack.pop()
                else:
                    stack.append(temp)
            else:
                stack.append(temp)
        if stack:
            return False
        else:
            return True


if __name__ == "__main__":
    solution = Solution()
    s = "(])"
    print(solution.isValid(s))

author : donghak park
contact : donghark03@naver.com

## 문제의 저작권은 LeetCode 사이트에 있습니다. 혹시 문제가 되는 부분이 있으면 연락 바랍니다.