Skip to content

[jungsiroo] Week 06 #888

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 4 commits into from
Jan 17, 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
44 changes: 44 additions & 0 deletions container-with-most-water/jungsiroo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
class Solution:
def maxArea(self, height: List[int]) -> int:
# Naive - 완전탐색
n = len(height)

"""
모든 조합을 계산한 후 최댓값 리턴
Tc : O(n^2)
Sc : O(1)

ret = 0

for i in range(n-1):
for j in range(i+1, n):
w = j - i
h = min(height[i], height[j])
ret = max(ret, w*h)
return ret
"""

# Better Solution
"""
투 포인터를 활용한 방법
포인터를 움직일 때는 더 작은 값을 가진 쪽이 한칸 움직여 그 높이를 높이는 방향 쪽으로 진행

Tc : O(n)
Sc : O(1)

"""
left, right = 0, n-1
ret = 0

while left < right:
w = right - left
h = min(height[left], height[right])
ret = max(ret, h*w)

if height[left] <= height[right]:
left += 1
else:
right -= 1
return ret


60 changes: 60 additions & 0 deletions design-add-and-search-words-data-structure/jungsiroo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
class Node:
def __init__(self, char=None):
self.is_end = False
self.children = {}

class WordDictionary:
"""
트라이를 활용
기본 문제와 다른 점은 search 할 때 "." 이 포함되어있는 것

따라서 . 이라면 해당 노드의 모든 자식을 모두 조회해야됨

addWord
w = len(word)
Tc : O(w)
Sc : O(w)

search
최악의 경우 case : xa, xb, xc, xd, .... xz 로 x의 다음 글자가 a~z일 때
search("x.") 라면 26개 모두를 찾아봐야됨
Tc : O(26^w)
Sc : O(w) (글자 길이만큼 재귀를 호출하기에)

"""
def __init__(self):
self.root = Node()

def addWord(self, word: str) -> None:
now = self.root

for ch in word:
if ch not in now.children:
now.children[ch] = Node(ch)
now = now.children[ch]
now.is_end = True

def search(self, word: str) -> bool:
def _recur_search(node, index):
if index == len(word):
return node.is_end

if word[index] == ".":
for ch in node.children:
if _recur_search(node.children[ch], index+1):
return True

if word[index] in node.children:
return _recur_search(node.children[word[index]], index+1)
return False

return _recur_search(self.root, 0)




# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)

44 changes: 44 additions & 0 deletions spiral-matrix/jungsiroo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from collections import deque

"""
BFS의 아이디어를 차용하여 풀이
Copy link
Contributor

Choose a reason for hiding this comment

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

풀이와 분석이 깔끔하고 헬퍼함수의 분리가 잘 되어 있는 것 같습니다 :)

이건 간단한 회전변환행렬을 이용한 예전 제 풀이인데, 혹시 관심 있으실까봐 남깁니다

Copy link
Contributor Author

Choose a reason for hiding this comment

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

와 행렬곱은 생각을 못했네요! 감사합니다~


끝에서부터 안쪽으로 돌아가야하기에 미리 돌아갈 방향 지정 : (dx, dy)
한칸씩 이동해가면서 범위 밖을 넘어갔거나 이미 visit한 데이터가 발견되면 방향을 꺾음

Tc : O(m*n)
Sc : O(m*n)
"""

# r, d, l ,u
dx = [0,1,0,-1]
dy = [1,0,-1,0]

class Solution:
def __init__(self):
self.m = 0
self.n = 0

def in_range(self, r, c):
if r<0 or r>=self.m or c<0 or c>=self.n:
return False
return True

def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
INF = int(1e9)
d = 0
self.m, self.n = len(matrix), len(matrix[0])
r, c = 0, 0

ret = []

for _ in range(self.m * self.n):
ret.append(matrix[r][c])
if not self.in_range(r+dx[d], c+dy[d]) or matrix[r+dx[d]][c+dy[d]] == INF:
d = (d+1)%4
matrix[r][c] = INF
r, c = r+dx[d], c+dy[d]

return ret


32 changes: 32 additions & 0 deletions valid-parentheses/jungsiroo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
class Solution:
def isValid(self, s: str) -> bool:
"""
스택을 이용한 간단한 풀이

s에 포함될 괄호들은 이미 정해져있는 상태이기에 딕셔너리 이용
이를 이용해 stack의 마지막 원소가 현재 괄호와 매치되는지를 정수를 통해 알 수 있음

마지막은 stack이 전부 비었을 때 True를 리턴

Time Complexity : O(n)
Space Complexity : O(n) (stack 변수)
"""


chars = {'(':1, '{':2, '[':3, ')':-1, '}':-2, ']':-3}
stack = []

for char in s:
if chars[char] > 0:
stack.append(char)
Comment on lines +16 to +21
Copy link
Contributor

Choose a reason for hiding this comment

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

이 부분이 좋네요!
value에 정수값을 두니까 조건문이 간단해져서 편해보입니다 :)

else:
if not stack : return False

if chars[stack[-1]] == -chars[char]:
stack.pop()
else:
return False

return not stack


Loading