File tree Expand file tree Collapse file tree 2 files changed +57
-2
lines changed
2024-06-June-LeetCoding-Challenge Expand file tree Collapse file tree 2 files changed +57
-2
lines changed Original file line number Diff line number Diff line change 9
9
| June 4 | [ 409. Longest Palindrome] ( https://leetcode.com/problems/longest-palindrome/ ) | Easy | Solved |
10
10
| June 5 | [ 1002. Find Common Characters] ( https://leetcode.com/problems/find-common-characters/ ) | Easy | Solved |
11
11
| June 6 | [ 846. Hand of Straights] ( https://leetcode.com/problems/hand-of-straights/ ) | Medium | Solved |
12
- | June 7 | [ ] ( ) | | |
12
+ | June 7 | [ 648. Replace Words ] ( https://leetcode.com/problems/replace-words/ ) | Medium | Solved |
13
13
| June 8 | [ ] ( ) | | |
14
14
| June 9 | [ ] ( ) | | |
15
15
| June 10 | [ ] ( ) | | |
39
39
| Level | Problems | Solved | Unsolved |
40
40
| --- | --- | --- | --- |
41
41
| Easy | 4 | 4 | 0 |
42
- | Medium | 2 | 2 | 0 |
42
+ | Medium | 3 | 3 | 0 |
43
43
| Hard | 0 | 0 | 0 |
Original file line number Diff line number Diff line change
1
+ from typing import List
2
+
3
+
4
+ class Node :
5
+ def __init__ (self ):
6
+ self .children = dict ()
7
+ self .is_word = False
8
+
9
+
10
+ class Trie :
11
+ def __init__ (self ):
12
+ self .root = Node ()
13
+
14
+ def insert (self , word : str ) -> None :
15
+ node = self .root
16
+ for ch in word :
17
+ node = node .children .setdefault (ch , Node ())
18
+ node .is_word = True
19
+
20
+ def shortest_prefix (self , word ) -> str :
21
+ node = self .root
22
+ prefix = str ()
23
+ for ch in word :
24
+ if ch not in node .children :
25
+ return word
26
+ node = node .children [ch ]
27
+ prefix += ch
28
+ if node .is_word :
29
+ return prefix
30
+ return word
31
+
32
+
33
+ class Solution :
34
+ def replaceWords (self , dictionary : List [str ], sentence : str ) -> str :
35
+ trie = Trie ()
36
+ for root in dictionary :
37
+ trie .insert (root )
38
+
39
+ sentence = sentence .split ()
40
+ sentence = map (trie .shortest_prefix , sentence )
41
+ return ' ' .join (sentence )
42
+
43
+
44
+ def main ():
45
+ dictionary = ['cat' , 'bat' , 'rat' ]
46
+ sentence = 'the cattle was rattled by the battery'
47
+ assert Solution ().replaceWords (dictionary , sentence ) == 'the cat was rat by the bat' # noqa: E501
48
+
49
+ dictionary = ['a' , 'b' , 'c' ]
50
+ sentence = 'aadsfasf absbs bbab cadsfafs'
51
+ assert Solution ().replaceWords (dictionary , sentence ) == 'a a b c'
52
+
53
+
54
+ if __name__ == '__main__' :
55
+ main ()
You can’t perform that action at this time.
0 commit comments