diff --git a/best-time-to-buy-and-sell-stock/sejineer.py b/best-time-to-buy-and-sell-stock/sejineer.py new file mode 100644 index 000000000..fd9907f4f --- /dev/null +++ b/best-time-to-buy-and-sell-stock/sejineer.py @@ -0,0 +1,15 @@ +""" +시간 복잡도: O(N) +공간 복잡도: O(1) +""" +class Solution: + def maxProfit(self, prices: List[int]) -> int: + buy = prices[0] + result = 0 + + for price in prices: + profit = price - buy + buy = min(buy, price) + result = max(profit, result) + + return result diff --git a/group-anagrams/sejineer.py b/group-anagrams/sejineer.py new file mode 100644 index 000000000..426282568 --- /dev/null +++ b/group-anagrams/sejineer.py @@ -0,0 +1,14 @@ +""" +시간 복잡도: O(N * K) N=문자열 개수, 평균 문자열 길이 = K (최대 100) +공간 복잡도: O(N * K) +""" +from collections import Counter, defaultdict + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + strs_dict = defaultdict(list) + for s in strs: + s_counter = Counter(s) + strs_dict[frozenset(s_counter.items())].append(s) + + return list(strs_dict.values()) diff --git a/implement-trie-prefix-tree/sejineer.py b/implement-trie-prefix-tree/sejineer.py new file mode 100644 index 000000000..d4de97b75 --- /dev/null +++ b/implement-trie-prefix-tree/sejineer.py @@ -0,0 +1,29 @@ +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 diff --git a/word-break/sejineer.py b/word-break/sejineer.py new file mode 100644 index 000000000..380a8a76a --- /dev/null +++ b/word-break/sejineer.py @@ -0,0 +1,18 @@ +""" +시간 복잡도: O(n * D * L) n = 문자열 길이, D = 사전 크기, L = 단어 평균 길이 +공간 복잡도: O(n) +""" +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + + @cache + def dfs(k: int) -> bool: + if k == len(s): + return True + for word in wordDict: + if s[k : k + len(word)] == word: + if dfs(k + len(word)): + return True + return False + + return dfs(0)