File tree Expand file tree Collapse file tree 5 files changed +90
-0
lines changed
best-time-to-buy-and-sell-stock
encode-and-decode-strings
implement-trie-prefix-tree Expand file tree Collapse file tree 5 files changed +90
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def maxProfit (self , prices : List [int ]) -> int :
3
+ minimum = prices [0 ]
4
+ answer = 0
5
+ for i in range (1 , len (prices )):
6
+ if minimum > prices [i ]:
7
+ minimum = prices [i ]
8
+ else :
9
+ diff = prices [i ] - minimum
10
+ if answer < diff :
11
+ answer = diff
12
+ return answer
Original file line number Diff line number Diff line change
1
+ class Codec :
2
+ def encode (self , strs : List [str ]) -> str :
3
+ return "\n " .join (strs )
4
+
5
+ def decode (self , s : str ) -> List [str ]:
6
+ return s .split ("\n " )
Original file line number Diff line number Diff line change
1
+ from collections import defaultdict
2
+
3
+ class Solution :
4
+ def groupAnagrams (self , strs : List [str ]) -> List [List [str ]]:
5
+ anagram_dict = defaultdict (list )
6
+ for string in strs :
7
+ anagram_dict [tuple (sorted (string ))].append (string )
8
+
9
+ answer = list (anagram_dict .values ())
10
+ return answer
Original file line number Diff line number Diff line change
1
+ class Node :
2
+ def __init__ (self , is_end = False ):
3
+ self .child = {}
4
+ self .is_end = is_end
5
+
6
+
7
+ class Trie :
8
+ def __init__ (self ):
9
+ self .root = Node ()
10
+
11
+ def insert (self , word : str ) -> None :
12
+ node = self .root
13
+ for ch in word :
14
+ if ch not in node .child :
15
+ node .child [ch ] = Node ()
16
+ node = node .child [ch ]
17
+ node .is_end = True
18
+
19
+ def search (self , word : str ) -> bool :
20
+ node = self .root
21
+ for ch in word :
22
+ if ch not in node .child :
23
+ return False
24
+ node = node .child [ch ]
25
+
26
+ return node .is_end
27
+
28
+ def startsWith (self , prefix : str ) -> bool :
29
+ node = self .root
30
+ for ch in prefix :
31
+ if ch not in node .child :
32
+ return False
33
+ node = node .child [ch ]
34
+
35
+ return True
36
+
37
+
38
+ # Your Trie object will be instantiated and called as such:
39
+ # obj = Trie()
40
+ # obj.insert(word)
41
+ # param_2 = obj.search(word)
42
+ # param_3 = obj.startsWith(prefix)
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def wordBreak (self , s : str , wordDict : List [str ]) -> bool :
3
+ checked = set ()
4
+
5
+ def dfs (idx ):
6
+ if idx in checked :
7
+ return
8
+ checked .add (idx )
9
+
10
+ if idx == len (s ):
11
+ return True
12
+
13
+ for word in wordDict :
14
+ word_len = len (word )
15
+ if s [idx : idx + word_len ] == word :
16
+ if dfs (idx + word_len ):
17
+ return True
18
+ return False
19
+
20
+ return dfs (0 )
You can’t perform that action at this time.
0 commit comments