Skip to content
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
25 changes: 25 additions & 0 deletions best-time-to-buy-and-sell-stock/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution:
"""
1. 브루트포스
2중 for문이라서 O(n^2)임.
prices의 길이가 10^5이므로 10^10이 되면서 시간초과가 발생

2. 이분탐색으로 가능할까 했지만 DP를 사용해야 하는 문제 같음
시간복잡도는 O(n)이 나옴
"""
"""
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
for i in range(len(prices)-1):
for j in range(i, len(prices)):
profit = prices[j] - prices[i]
max_profit = max(max_profit, profit)
return max_profit
"""
def maxProfit(self, prices: List[int]) -> int:
max_profit = 0
min_price = prices[0]
Copy link
Contributor

Choose a reason for hiding this comment

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

prices가 빈 배열일 경우 prices[0] 접근에서 IndexError 발생 가능 → 입력 검증 필요

Copy link
Contributor Author

Choose a reason for hiding this comment

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

배열의 길이는 1이상이라서 빈 배열이 나올 경우가 없어 검증이 필요없을 것 같습니다.

Copy link
Contributor

Choose a reason for hiding this comment

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

아 제가 조건을 못 봤네요. 이 문제에서는 해당 사항 고려하지 않으셔도 됩니다.

for price in prices:
max_profit = max(max_profit, price - min_price)
min_price = min(price, min_price)
return max_profit
14 changes: 14 additions & 0 deletions encode-and-decode-strings/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Solution:
"""
@param: strs: a list of strings
@return: encodes a list of strings to a single string.
"""
def encode(self, strs):
return "secretKey!@#".join(strs)

"""
@param: str: A string
@return: decodes a single string to a list of strings
"""
def decode(self, str):
return str.split("secretKey!@#")
12 changes: 12 additions & 0 deletions group-anagrams/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from collections import defaultdict

class Solution:
"""
1. 정렬된 값이 딕셔너리에 있으면 리스트 형식으로 삽입
"""
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dict_strs = defaultdict(list)

for word in strs:
dict_strs[str(sorted(word))].append(word)
Copy link
Contributor

Choose a reason for hiding this comment

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

str(sorted(word)) 대신 tuple(sorted(word))가 더 효율적

Copy link
Contributor Author

Choose a reason for hiding this comment

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

좋은 정보 감사합니다!

return list(dict_strs.values())
35 changes: 35 additions & 0 deletions implement-trie-prefix-tree/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class Trie:

def __init__(self):
self.root = {"$": True}

def insert(self, word: str) -> None:
node = self.root
for ch in word:
if ch not in node:
node[ch] = {"$": False}
node = node[ch]
node["$"] = True

def search(self, word: str) -> bool:
node = self.root
for ch in word:
if ch not in node:
return False
node = node[ch]
return node["$"]

def startsWith(self, prefix: str) -> bool:
node = self.root
for ch in prefix:
if ch not in node:
return False
node = node[ch]
return True


# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
19 changes: 19 additions & 0 deletions word-break/hu6r1s.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import java.util.*;

class Solution {
Copy link
Contributor

Choose a reason for hiding this comment

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

dp 로 가능한 문제였군요. 많이 배워갑니다. 감사합니다!

public boolean wordBreak(String s, List<String> wordDict) {
Set<String> wordSet = new HashSet<>(wordDict);
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;

for (int i = 1; i < s.length() + 1; i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && (wordSet.contains(s.substring(j, i)))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}
14 changes: 14 additions & 0 deletions word-break/hu6r1s.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
word_set = set(wordDict) # O(1) 조회를 위해 set으로 변환
n = len(s)
dp = [False] * (n + 1)
dp[0] = True # 공집합은 항상 가능

for i in range(1, n + 1):
for j in range(i):
if dp[j] and s[j:i] in word_set:
dp[i] = True
break # i번째까지 나눌 수 있으면 더 확인할 필요 없음

return dp[-1]