Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions container-with-most-water/river20s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution:
def maxArea(self, height: List[int]) -> int:
# 시작과 끝 선분을 포인터로 두고
# 두 선분으로 만들 수 있는 넓이:
# 너비 = right - left
# 높이 = min(height[left], height[right])
# 넓이 = 너비 * 높이의 최대 값을 구하는 문제
# Time Complexity: O(n)
# 두 포인터가 한 칸씩만 이동하며 서로 만날 때 루프 종료
# Space Complexity: O(1)
n = len(height)
left = 0 # 왼쪽(시작) 포인터
right = n - 1 # 오른쪽(끝) 포인터
max_area = 0

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

문제풀이에 대한 주석을 상세히 적어주셔서 코드를 이해하기 쉬웠습니다. 👍

while left < right:
# 현재 높이는 두 직선 중 낮은 쪽
current_height = min(height[left], height[right])
# 현재 너비는 오른쪽 점과 왼쪽 점의 차
current_width = right - left
# 넓이 = 높이 * 너비
current_area = current_height * current_width
# 최대 넓이라면 업데이트
max_area = max(max_area, current_area)
# 포인터 이동 후 탐색
# 둘 중 더 낮은 쪽의 포인터를 안으로 움직여서 넓이 계산
# 더 큰 넓이를 찾는 것이 목표, 포인터를 안으로 움직이면 너비는 무조건 감소
# 높이라도 증가할 가능성이 있어야 하므로 기존 낮은 높이가 늘어날 가능성에 배팅
# 둘이 같다면 오른쪽 이동(아무쪽이나 가능)
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_area
57 changes: 57 additions & 0 deletions valid-parentheses/river20s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
class Stack:
def __init__(self):
self.data = []

def is_empty(self):
return len(self.data) == 0

def push(self, element):
self.data.append(element)

def pop(self):
if not self.is_empty():
return self.data.pop()
else:
return None

def peek(self):
if not self.is_empty():
return self.data[-1]
else:
return None
# <<<--- Stack 구현 ---<<<
# >>>--- 답안 Solution --->>>
class Solution:
# 스택을 활용해 괄호 유효 검사
# Time Complexity: O(n)
# Space Complexity: O(n)
def __init__(self):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Solution 클래스의 __init__ 메서드에서 정의한 괄호 맵핑은 클래스 변수로 선언해도 좋을 것 같습니다.

self._opening_brackets = '([{'
self._closing_brackets = ')]}'
self._matching_map = {')': '(', ']': '[', '}': '{'}

def isValid(self, s: str) -> bool:
stack = Stack()
for char in s:
# 여는 괄호라면 스택에 push
if self._is_opening(char):
stack.push(char)
# 닫는 괄호라면
# 마지막 열린 괄호와 유형 일치 확인
elif self._is_closing(char):
if stack.is_empty():
# 스택이 비어 있으면 False 반환
return False
last_open_bracket = stack.pop()
if not self._is_match(last_open_bracket, char):
return False
return stack.is_empty()

def _is_opening(self, char: str) -> bool:
return char in self._opening_brackets

def _is_closing(self, char: str) -> bool:
return char in self._closing_brackets

def _is_match(self, open_bracket: str, close_bracket: str) -> bool:
return self._matching_map.get(close_bracket) == open_bracket
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

코드가 체계적이고 객체지향적인 방식으로 잘 작성하신것 같아요. Stack 클래스를 직접 구현하고, Solution 클래스에서 이를 활용한 점이 인상적입니다. 👍

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_is_match 메서드에서 get 메서드를 사용했는데, 이미 _is_closing에서 유효한 괄호임을 확인했다면 직접 접근해도 안전할 것 같습니다. 😀