Skip to content

Commit cd99cbf

Browse files
authored
Merge pull request #875 from pmjuu/main
[Lyla] Week 05
2 parents 845cdbd + 6f9ddfd commit cd99cbf

File tree

6 files changed

+201
-1
lines changed

6 files changed

+201
-1
lines changed
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# 시간 복잡도:
2+
# - 배열을 한 번 순회하므로 O(n) (n은 prices 배열의 길이)
3+
4+
# 공간 복잡도:
5+
# - 추가 변수 2개(min_price, max_profit)를 사용하므로 O(1)
6+
7+
from typing import List
8+
9+
10+
class Solution:
11+
def maxProfit(self, prices: List[int]) -> int:
12+
buy = float('inf')
13+
profit = 0
14+
15+
for price in prices:
16+
if price < buy:
17+
buy = price
18+
else:
19+
profit = max(profit, price - buy)
20+
21+
return profit

encode-and-decode-strings/pmjuu.py

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# encode 메서드:
2+
# 시간 복잡도: O(N)
3+
# - 각 문자열을 한 번씩 순회하며 길이와 내용을 처리하므로, 모든 문자열 길이의 합에 비례.
4+
# 공간 복잡도: O(N)
5+
# - 인코딩된 결과 문자열을 저장하기 위해 추가 공간 사용.
6+
7+
# decode 메서드:
8+
# 시간 복잡도: O(N)
9+
# - 인코딩된 문자열을 처음부터 끝까지 한 번 순회하며 파싱하므로, 입력 문자열 길이에 비례.
10+
# - s.find('#', i)는 인덱스 i부터 다음 #를 찾음.
11+
# - 여러 번의 find 호출이 있더라도 각 호출마다 전체 문자열을 다시 탐색하지 않고 이전 탐색 이후의 부분만 탐색하게 되어, 모든 find 호출을 합한 전체 탐색 거리는 인코딩된 문자열의 전체 길이 n에 해당함. 전체 시간은 O(n)에 수렴.
12+
# 공간 복잡도: O(N)
13+
# - 디코딩된 문자열 리스트를 구성하기 위해 추가 공간 사용.
14+
15+
16+
class Solution:
17+
"""
18+
@param strs: a list of strings
19+
@return: encodes a list of strings to a single string.
20+
"""
21+
def encode(self, strs):
22+
encoded_str = ""
23+
24+
for s in strs:
25+
encoded_str += (str(len(s)) + "#" + s)
26+
27+
return encoded_str
28+
29+
"""
30+
@param s: A string
31+
@return: decodes a single string to a list of strings
32+
"""
33+
def decode(self, s):
34+
decoded_list = []
35+
i = 0
36+
while i < len(s):
37+
j = s.find("#", i)
38+
length = int(s[i:j])
39+
i = j + 1
40+
decoded_list.append(s[i:i + length])
41+
i += length
42+
43+
return decoded_list
44+
45+
46+
def main():
47+
sol = Solution()
48+
49+
# 테스트 예시 1
50+
input_strings1 = ["lint", "code", "love", "you"]
51+
print("===== Example 1 =====")
52+
print("Original: ", input_strings1)
53+
encoded_str1 = sol.encode(input_strings1)
54+
print("Encoded: ", encoded_str1)
55+
decoded_list1 = sol.decode(encoded_str1)
56+
print("Decoded: ", decoded_list1)
57+
print()
58+
59+
# 테스트 예시 2
60+
input_strings2 = ["1234567890a", "we", "say", "#", "yes"]
61+
print("===== Example 2 =====")
62+
print("Original: ", input_strings2)
63+
encoded_str2 = sol.encode(input_strings2)
64+
print("Encoded: ", encoded_str2)
65+
decoded_list2 = sol.decode(encoded_str2)
66+
print("Decoded: ", decoded_list2)
67+
print()
68+
69+
70+
if __name__ == "__main__":
71+
main()

group-anagrams/pmjuu.py

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# 시간 복잡도: O(n * m log m)
2+
# - n: 문자열 배열의 길이, m: 각 문자열의 최대 길이
3+
# - 각 문자열을 정렬하는 데 O(m log m) 시간이 걸리며, 모든 문자열에 대해 이를 수행
4+
# - 문제에서 m 이 최대 100이므로, 정렬 비용은 상수에 가깝게 볼 수도 있음 (m = 100인 상황에서 100 * log(100)는 약 664 정도)
5+
6+
# 공간 복잡도: O(n * m)
7+
# - 정렬된 문자열(길이 최대 m)을 키로 사용하는 딕셔너리에 최대 n개의 키가 생길 수 있음
8+
# - 각 키에 대해 원본 문자열들을 저장하므로 O(n * m) 크기의 공간을 사용
9+
10+
from collections import defaultdict
11+
from typing import List
12+
13+
14+
class Solution:
15+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
16+
anagram_map = defaultdict(list)
17+
18+
for word in strs:
19+
sorted_word = ''.join(sorted(word))
20+
anagram_map[sorted_word].append(word)
21+
22+
return list(anagram_map.values())

implement-trie-prefix-tree/pmjuu.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# 시간 복잡도:
2+
# - insert(word): O(m)
3+
# - m은 word의 길이입니다.
4+
# - 각 문자에 대해 트리를 탐색하거나 새 노드를 추가하므로 O(m) 시간이 걸립니다.
5+
#
6+
# - search(word): O(m)
7+
# - m은 word의 길이입니다.
8+
# - 트리의 각 문자 노드를 탐색하므로 O(m) 시간이 걸립니다.
9+
#
10+
# - startsWith(prefix): O(m)
11+
# - m은 prefix의 길이입니다.
12+
# - 트리의 각 문자 노드를 탐색하므로 O(m) 시간이 걸립니다.
13+
#
14+
# 공간 복잡도:
15+
# - O(n * m)
16+
# - n은 트리에 삽입된 단어의 개수입니다.
17+
# - m은 각 단어의 평균 길이입니다.
18+
# - 각 단어의 문자에 대해 새로운 노드를 생성하므로 O(n * m) 공간이 필요합니다.
19+
20+
21+
class Trie:
22+
23+
def __init__(self):
24+
self.children = {}
25+
self.is_end_of_word = False
26+
27+
def insert(self, word: str) -> None:
28+
current = self
29+
30+
for char in word:
31+
if char not in current.children:
32+
current.children[char] = Trie()
33+
current = current.children[char]
34+
35+
current.is_end_of_word = True
36+
37+
def search(self, word: str) -> bool:
38+
current = self
39+
40+
for char in word:
41+
if char not in current.children:
42+
return False
43+
current = current.children[char]
44+
45+
return current.is_end_of_word
46+
47+
def startsWith(self, prefix: str) -> bool:
48+
current = self
49+
50+
for char in prefix:
51+
if char not in current.children:
52+
return False
53+
current = current.children[char]
54+
55+
return True

word-break/pmjuu.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
시간 복잡도:
3+
- 외부 루프는 O(n), 내부 루프는 최악의 경우 각 i에 대해 O(n)만큼 실행됩니다. (n: 문자열 s의 길이)
4+
- s[j:i]를 wordSet에서 찾는 작업은 O(1)입니다 (set 사용).
5+
- 전체 시간 복잡도: O(n^2).
6+
7+
공간 복잡도:
8+
- DP 배열은 O(n)의 공간을 차지합니다.
9+
- wordSet은 wordDict에 있는 모든 문자의 총 길이를 기준으로 O(m)의 공간을 차지합니다. (m: wordDict의 단어 수)
10+
- 전체 공간 복잡도: O(n + m).
11+
"""
12+
13+
from typing import List
14+
15+
16+
class Solution:
17+
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
18+
wordSet = set(wordDict)
19+
n = len(s)
20+
21+
dp = [False] * (n + 1)
22+
dp[0] = True
23+
24+
for i in range(1, n + 1):
25+
for j in range(i):
26+
if dp[j] and s[j:i] in wordSet:
27+
dp[i] = True
28+
break
29+
30+
return dp[n]

word-search/pmjuu.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,14 @@ def search(row, col, word_idx, visited):
5151
# => 총 공간 복잡도: O(k)
5252

5353

54+
from collections import Counter
55+
5456
class Solution:
5557
def exist(self, board: list[list[str]], word: str) -> bool:
5658
n, m = len(board), len(board[0])
5759
word_length = len(word)
5860

5961
# 조기 종료: board에 word를 구성할 충분한 문자가 있는지 확인
60-
from collections import Counter
6162
board_counter = Counter(char for row in board for char in row)
6263
word_counter = Counter(word)
6364
if any(word_counter[char] > board_counter[char] for char in word_counter):

0 commit comments

Comments
 (0)