File tree Expand file tree Collapse file tree 4 files changed +76
-0
lines changed
best-time-to-buy-and-sell-stock
implement-trie-prefix-tree Expand file tree Collapse file tree 4 files changed +76
-0
lines changed Original file line number Diff line number Diff line change 1+ """
2+ 시간 복잡도: O(N)
3+ 공간 복잡도: O(1)
4+ """
5+ class Solution :
6+ def maxProfit (self , prices : List [int ]) -> int :
7+ buy = prices [0 ]
8+ result = 0
9+
10+ for price in prices :
11+ profit = price - buy
12+ buy = min (buy , price )
13+ result = max (profit , result )
14+
15+ return result
Original file line number Diff line number Diff line change 1+ """
2+ 시간 복잡도: O(N * K) N=문자열 개수, 평균 문자열 길이 = K (최대 100)
3+ 공간 복잡도: O(N * K)
4+ """
5+ from collections import Counter , defaultdict
6+
7+ class Solution :
8+ def groupAnagrams (self , strs : List [str ]) -> List [List [str ]]:
9+ strs_dict = defaultdict (list )
10+ for s in strs :
11+ s_counter = Counter (s )
12+ strs_dict [frozenset (s_counter .items ())].append (s )
13+
14+ return list (strs_dict .values ())
Original file line number Diff line number Diff line change 1+ class Trie :
2+
3+ def __init__ (self ):
4+ self .root = {"$" : True }
5+
6+ def insert (self , word : str ) -> None :
7+ node = self .root
8+ for ch in word :
9+ if ch not in node :
10+ node [ch ] = {"$" : False }
11+ node = node [ch ]
12+ node ["$" ] = True
13+
14+
15+ def search (self , word : str ) -> bool :
16+ node = self .root
17+ for ch in word :
18+ if ch not in node :
19+ return False
20+ node = node [ch ]
21+ return node ["$" ]
22+
23+ def startsWith (self , prefix : str ) -> bool :
24+ node = self .root
25+ for ch in prefix :
26+ if ch not in node :
27+ return False
28+ node = node [ch ]
29+ return True
Original file line number Diff line number Diff line change 1+ """
2+ 시간 복잡도: O(n * D * L) n = 문자열 길이, D = 사전 크기, L = 단어 평균 길이
3+ 공간 복잡도: O(n)
4+ """
5+ class Solution :
6+ def wordBreak (self , s : str , wordDict : List [str ]) -> bool :
7+
8+ @cache
9+ def dfs (k : int ) -> bool :
10+ if k == len (s ):
11+ return True
12+ for word in wordDict :
13+ if s [k : k + len (word )] == word :
14+ if dfs (k + len (word )):
15+ return True
16+ return False
17+
18+ return dfs (0 )
You can’t perform that action at this time.
0 commit comments