You are given a list of strings dictionary
where each string is a word, and a string sentence
containing words separated by spaces. You want to replace all the words in the sentence with the root form of the words found in the dictionary.
If a word has multiple roots in the dictionary, replace it with the shortest one.
Return the sentence with the words replaced.
Input: dictionary = ["cat", "bat", "rat"], sentence = "the cattle was rattled by the battery"
Output: "the cat was rat by the bat"
Input: dictionary = ["a", "b", "c"], sentence = "aadsfasf absbs bbab cadsfafs"
Output: "a a b c"
Input: dictionary = ["a", "aa", "aaa", "aaaa"], sentence = "a aa a aaaa aaa aaa aaa aaaaaa bbb baba ababa"
Output: "a a a a a a a a bbb baba a"
1 <= dictionary.length <= 1000
1 <= dictionary[i].length <= 100
dictionary[i]
and sentence
consist of only lowercase letters and spaces.class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_word = True
def search_root(self, word):
node = self.root
root = ""
for char in word:
if char not in node.children:
return word
node = node.children[char]
root += char
if node.is_word:
return root
return word
def replaceWords(dictionary, sentence):
trie = Trie()
for word in dictionary:
trie.insert(word)
words = sentence.split()
replaced_sentence = []
for word in words:
replaced_sentence.append(trie.search_root(word))
return " ".join(replaced_sentence)
# Example usage:
dictionary = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
print(replaceWords(dictionary, sentence)) # Output: "the cat was rat by the bat"
n
words each of maximum length l
, this is O(n * l)
.m
words in the sentence, each of max length l
, this is O(m * l)
.O(n * l + m * l)
, where n
is the size of the dictionary, m
is the number of words in the sentence, and l
is the average length of the words.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?