From bd7583dc611da41967e1998a78cb9409eab7138f Mon Sep 17 00:00:00 2001 From: jongwanra Date: Tue, 26 Aug 2025 07:14:26 +0900 Subject: [PATCH 1/2] add valid-parentheses solution --- valid-parentheses/jongwanra.py | 46 ++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 valid-parentheses/jongwanra.py diff --git a/valid-parentheses/jongwanra.py b/valid-parentheses/jongwanra.py new file mode 100644 index 000000000..c3489c152 --- /dev/null +++ b/valid-parentheses/jongwanra.py @@ -0,0 +1,46 @@ +""" +[Problem] +https://leetcode.com/problems/valid-parentheses/ + +[Brainstorming] +1. 여는 괄호가 나올 경우에 Stack에 Push한다. +2. 닫는 괄호가 나왔을 경우에 Stack 가장 위에 여는 괄호와 일치 여부를 확인한다. + +이렇게 했을 때, 시간 복잡도는 O(N)으로 예상한다. (여기서 N은 s.length) + +[Complexity] +Time: O(N), N = s.length +Space: O(N), N = stack.length +""" +from os import popen + + +class Solution: + def isValid(self, s: str) -> bool: + bracket_dict = {'(':')', '{':'}', '[':']'} + stack = [] + for bracket in s: + # 여는 괄호인 경우 Stack 추가 + if bracket in bracket_dict: + stack.append(bracket) + continue + + # 닫는 괄호인 경우 + if not stack or bracket_dict[stack.pop()] != bracket: + return False + + return not stack + +sol = Solution() + +# Normal Case +print(sol.isValid("()") == True) +print(sol.isValid("()[]{}") == True) +print(sol.isValid("(]") == False) +print(sol.isValid("([])") == True) +print(sol.isValid("([)]") == False) + +# Edge Case +print(sol.isValid("(") == False) +print(sol.isValid("]") == False) + From b45e7f69a0098d58c15fac949fd22283aade0505 Mon Sep 17 00:00:00 2001 From: jongwanra Date: Mon, 1 Sep 2025 07:14:25 +0900 Subject: [PATCH 2/2] refactor: apply reviewer suggestions to valid-parentheses solution --- valid-parentheses/jongwanra.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/valid-parentheses/jongwanra.py b/valid-parentheses/jongwanra.py index c3489c152..1ae426fcc 100644 --- a/valid-parentheses/jongwanra.py +++ b/valid-parentheses/jongwanra.py @@ -12,8 +12,6 @@ Time: O(N), N = s.length Space: O(N), N = stack.length """ -from os import popen - class Solution: def isValid(self, s: str) -> bool: @@ -23,11 +21,12 @@ def isValid(self, s: str) -> bool: # 여는 괄호인 경우 Stack 추가 if bracket in bracket_dict: stack.append(bracket) - continue - # 닫는 괄호인 경우 - if not stack or bracket_dict[stack.pop()] != bracket: - return False + else: + if not stack: + return False + if bracket_dict[stack.pop()] != bracket: + return False return not stack @@ -44,3 +43,4 @@ def isValid(self, s: str) -> bool: print(sol.isValid("(") == False) print(sol.isValid("]") == False) +