File tree 4 files changed +101
-0
lines changed
best-time-to-buy-and-sell-stock
implement-trie-prefix-tree
4 files changed +101
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Time complexity O(n)
3
+ Space complexity O(1)
4
+
5
+ Dynamic programming
6
+ """
7
+
8
+ class Solution :
9
+ def maxProfit (self , prices : List [int ]) -> int :
10
+ max_profit = 0
11
+ min_price = prices [0 ]
12
+ for p in prices :
13
+ max_profit = max (max_profit , p - min_price )
14
+ min_price = min (min_price , p )
15
+
16
+ return max_profit
Original file line number Diff line number Diff line change
1
+ """
2
+ Time complexity O(n)
3
+ --> O(n * wlog(w))
4
+ n : 주어지는 단어 개수
5
+ w : 평균 단어 길이
6
+
7
+ Space compexity O(n)
8
+
9
+ hash table, sorting
10
+ """
11
+
12
+ class Solution :
13
+ def groupAnagrams (self , strs : List [str ]) -> List [List [str ]]:
14
+ group = defaultdict (list )
15
+ for s in strs :
16
+ sorted_str = str (sorted (s ))
17
+ group [sorted_str ].append (s )
18
+
19
+ return list (group .values ())
Original file line number Diff line number Diff line change
1
+ """
2
+ Time complexity O(n)
3
+ """
4
+
5
+ class Node :
6
+ def __init__ (self , end = False ):
7
+ self .children = {} # hash table
8
+ self .end = end
9
+
10
+ class Trie :
11
+ def __init__ (self ):
12
+ self .root = Node (end = True )
13
+
14
+ def insert (self , word : str ) -> None :
15
+ node = self .root
16
+
17
+ for c in word :
18
+ if c not in node .children :
19
+ node .children [c ] = Node ()
20
+ node = node .children [c ]
21
+ node .end = True
22
+
23
+ def search (self , word : str ) -> bool :
24
+ node = self .root
25
+ for c in word :
26
+ if c not in node .children :
27
+ return False
28
+ node = node .children [c ]
29
+ if node .end :
30
+ return True
31
+ return False
32
+
33
+ def startsWith (self , prefix : str ) -> bool :
34
+ node = self .root
35
+ for c in prefix :
36
+ if c not in node .children :
37
+ return False
38
+ node = node .children [c ]
39
+ return True
Original file line number Diff line number Diff line change
1
+ """
2
+ Time complexity O(n*m) n: len(s), m:len(wordDict)
3
+ Space compexity O(n)
4
+
5
+ dynamic programming
6
+ """
7
+
8
+ class Solution :
9
+ def wordBreak (self , s : str , wordDict : List [str ]) -> bool :
10
+ dp = [False for _ in range (len (s ))]
11
+ for i in range (len (s )):
12
+ flag = False
13
+ for word in wordDict :
14
+ n = len (word )
15
+ if i - n + 1 < 0 :
16
+ continue
17
+ if s [i - n + 1 :i + 1 ] != word :
18
+ continue
19
+ if i - n + 1 == 0 :
20
+ flag = True
21
+ break
22
+ elif i - n + 1 > 0 :
23
+ if dp [i - n ]:
24
+ flag = True
25
+ break
26
+ dp [i ] = flag
27
+ return dp [- 1 ]
You can’t perform that action at this time.
0 commit comments