Skip to content

[river20s] WEEK 06 solutions #1419

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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

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):
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