-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0648-replace-words.py
More file actions
65 lines (53 loc) · 1.77 KB
/
0648-replace-words.py
File metadata and controls
65 lines (53 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# time complexity: O(d*w + s*w^2)
# space complexity: O(d*w + s*w)
from typing import List
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
dictSet = set(dictionary)
result = []
for word in sentence.split(" "):
for wordIdx in range(len(word)+1):
if word[:wordIdx] in dictSet:
result.append(word[:wordIdx])
break
if wordIdx == len(word):
result.append(word[:wordIdx])
return " ".join(result)
# time complexity: O(n + m)
# space complexity: O(m)
class TrieNode:
def __init__(self, char=""):
self.char = char
self.children = {}
self.isEnd = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str):
node = self.root
for c in word:
if c not in node.children:
node.children[c] = TrieNode()
node = node.children[c]
node.isEnd = True
def replace(self, word: str):
node = self.root
for i, c in enumerate(word):
if c not in node.children:
return word
node = node.children[c]
if node.isEnd:
return word[:i + 1]
return word
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
trie = Trie()
for prefix in dictionary:
trie.insert(prefix)
newList = sentence.split()
for i in range(len(newList)):
newList[i] = trie.replace(newList[i])
return " ".join(newList)
dictionary = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
print(Solution().replaceWords(dictionary, sentence))