Skip to content

Commit ed992b7

Browse files
committed
Jun 7
1 parent 81480bc commit ed992b7

File tree

2 files changed

+57
-2
lines changed

2 files changed

+57
-2
lines changed

2024-06-June-LeetCoding-Challenge/README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
| June 4 | [409. Longest Palindrome](https://leetcode.com/problems/longest-palindrome/) | Easy | Solved |
1010
| June 5 | [1002. Find Common Characters](https://leetcode.com/problems/find-common-characters/) | Easy | Solved |
1111
| 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 |
1313
| June 8 | []() | | |
1414
| June 9 | []() | | |
1515
| June 10 | []() | | |
@@ -39,5 +39,5 @@
3939
| Level | Problems | Solved | Unsolved |
4040
| --- | --- | --- | --- |
4141
| Easy | 4 | 4 | 0 |
42-
| Medium | 2 | 2 | 0 |
42+
| Medium | 3 | 3 | 0 |
4343
| Hard | 0 | 0 | 0 |
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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()

0 commit comments

Comments
 (0)