LeetCode/Top Interview 150

20. Valid Parentheses

hyunkookim 2024. 12. 2. 17:57

20. Valid Parentheses

 

class Solution:
    def isValid(self, s: str) -> bool:
        # 닫힌 괄호를 키로 하고, 해당하는 열린 괄호를 값으로 가지는 딕셔너리
        parentheses = {')': '(', '}': '{', ']': '['}

        # 괄호를 추적하기 위한 스택 초기화
        stack = []

        # for i in range(len(s)):
        #     if s[i] in parentheses and len(stack) >0:
        #         if stack[-1] == parentheses[s[i]]:
        #             stack.pop()
        #         else:
        #             return False
        #     else:
        #         stack.append(s[i])
        # return len(stack) == 0

        # 문자열 s의 각 문자를 순회
        for c in s:
            # 닫힌 괄호인지 확인하고 스택이 비어 있지 않은 경우 처리
            if c in parentheses and len(stack) > 0:
                # 스택의 최상단 값(가장 최근의 열린 괄호)이 닫힌 괄호와 짝이 맞는지 확인
                if stack[-1] == parentheses[c]:
                    stack.pop()  # 짝이 맞으면 스택에서 최상단 값 제거
                else:
                    return False  # 짝이 맞지 않으면 유효하지 않은 문자열로 판단
            else:
                # 열린 괄호이거나, 스택이 비어있는 경우 스택에 추가
                stack.append(c)

        # 모든 문자를 처리한 후, 스택이 비어있다면 유효한 문자열
        return len(stack) == 0

 

https://youtu.be/WTzjTskDFMg?si=Pfn_fDQwzEFx4E3g

 

'LeetCode > Top Interview 150' 카테고리의 다른 글

128. Longest Consecutive Sequence  (0) 2024.12.03
155. Min Stack  (0) 2024.12.02
228. Summary Ranges  (0) 2024.12.02
289. Game of Life  (0) 2024.12.02
73. Set Matrix Zeroes  (0) 2024.12.02