Skip to content

[yyyyyyyyyKim] WEEK 06 solutions #1431

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

Merged
merged 6 commits into from
May 10, 2025
Merged
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
20 changes: 20 additions & 0 deletions container-with-most-water/yyyyyyyyyKim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution:
def maxArea(self, height: List[int]) -> int:

# 투포인터(two pointer) : 시간복잡도 O(n)
left, right = 0, len(height)-1
answer = 0

while left < right:
width = right - left # 인덱스 차이가 두 벽 사이의 거리(너비)
h = min(height[left], height[right]) # 더 낮은 벽을 기준으로 물을 채울 수 있음(높이)

answer = max(answer, width * h) # 최대 넓이 업데이트

# 포인터 이동(더 낮은 값을 가진 포인터를 이동)
if height[left] < height[right]:
left += 1
else:
right -= 1

return answer
67 changes: 67 additions & 0 deletions design-add-and-search-words-data-structure/yyyyyyyyyKim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""
TrieNode: 한 글자를 담는 노드
- children: 자식노드들 저장하는 딕셔너리
- end: 해당 노드에서 단어가 끝나는지 여부
"""
class TrieNode:
# Trie 노드 초기화
def __init__(self):
self.children = {} # 자식 노드 저장
self.end = False # 단어의 끝인지 표시

"""
Trie(트라이)구조, DFS, 재귀
- addWord : 단어를 Trie에 삽입
- search : 단어가 Trie에 존재하는지 검색
"""
class WordDictionary:

# Trie 자료구조 초기화(루트 노드 생성)
def __init__(self):
# Trie의 시작(빈 루트 노드 생성)
self.root = TrieNode()

def addWord(self, word: str) -> None:
node = self.root # 단어 삽입의 시작 위치 = 루트 노드

# 단어의 글자 하나하나를 Trie에 삽입
for i in word:
# 글자가 자식 노드에 없으면 새로운 노드 생성해서 뻗어가기
if i not in node.children:
node.children[i] = TrieNode()

node = node.children[i] # 다음 글자(노드)로 이동

node.end = True # 단어 삽입 완료, 현재 노드에서 단어의 끝 표시(True)


def search(self, word: str) -> bool:

def dfs(node,i):
# 단어를 다 돌고 마지막 노드가 단어의 끝이면 node.end는 True
if i == len(word):
return node.end

if word[i] == ".":
# "." 일 경우 모든 자식 노드 대상으로 재귀 탐색
for j in node.children.values():
if dfs(j, i+1):
return True
else:
# "."이 아닌 경우 자식노드에 있는지 확인.
# 있으면 다음 글자 탐색, 없으면 False 리턴
if word[i] in node.children:
return dfs(node.children[word[i]], i+1)
else:
return False

# 일치하는 단어가 없는 경우에 대비한 예외 처리
return False

# DFS시작(루트 노드부터 탐색)
return dfs(self.root, 0)

# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
16 changes: 16 additions & 0 deletions longest-increasing-subsequence/yyyyyyyyyKim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:

# DP(각 인덱스를 끝으로 하는 LIS의 최대 길이 저장)
dp = [1]*len(nums) # 초기값은 1(자신 하나만 있을 경우)

for i in range(len(nums)):
for j in range(i):
# 현재값(nums[i])이 이전값(nums[j])보다 크면 dp[i]업데이트
if nums[i] > nums[j]:
dp[i] = max(dp[i],dp[j]+1)

# dp에 저장된 최대값 리턴
return max(dp)

# 시간복잡도 O(n^2), 공간복잡도 O(n)
35 changes: 35 additions & 0 deletions spiral-matrix/yyyyyyyyyKim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:

answer = []

# 경계값
top, bottom = 0, len(matrix)-1
left, right = 0, len(matrix[0])-1

# 시계방향으로 한 바퀴씩 돌기
while top <= bottom and left <= right:

# 오른쪽 이동
for i in range(left,right+1):
answer.append(matrix[top][i])
top += 1

# 아래로 이동
for i in range(top,bottom+1):
answer.append(matrix[i][right])
right -= 1

# 왼쪽 이동
if top <= bottom: # 위에서 top을 증가시켰기 때문에 다시 검사(아직 아래쪽에 행이 남아있는 경우에만 수행)
for i in range(right,left-1,-1):
answer.append(matrix[bottom][i])
bottom -= 1

# 위로 이동
if left <= right: # 위에서 right를 감소시켰기 때문에 다시 검사(아직 왼쪽에 열이 남아있는 경우에만 수행)
for i in range(bottom,top-1,-1):
answer.append(matrix[i][left])
left += 1

return answer
34 changes: 34 additions & 0 deletions valid-parentheses/yyyyyyyyyKim.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class Solution:
def isValid(self, s: str) -> bool:

# Stack
stack = []
i = 0

while i < len(s):
# 여는 괄호일 경우 스택에 추가
if s[i] == "(" or s[i] == "{" or s[i] == "[":
stack.append(s[i])

# 닫는 괄호일 경우
else:
# 스택이 비어 있을경우 짝이 맞지않으므로 False 리턴
if not stack:
return False

# 스택 마지막에 짝맞는 여는 괄호가 없으면 False
if s[i] == ")" and stack[-1] != "(":
return False
elif s[i] == "}" and stack[-1] != "{":
return False
elif s[i] == "]" and stack[-1] != "[":
return False

# 짝이 맞으면 pop
stack.pop()

# 다음 글자로 이동
i += 1

# 문자열을 다 돌고, 스택도 비어있다면 True 리턴
return not stack