In English, we have a concept called root, which can be followed by some other words to form another longer word - let’s call this word successor. For example, the root an, followed by other, which can form another word another.
Now, given a dictionary consisting of many roots and a sentence. You need to replace all the successor in the sentence with the root forming it. If a successor has many roots can form it, replace it with the root with the shortest length.
You need to output the sentence after the replacement.
Example 1:
1 2 3
Input: dict = ["cat", "bat", "rat"] sentence = "the cattle was rattled by the battery" Output: "the cat was rat by the bat"
classSolution(object): defreplaceWords(self, roots, sentence): _trie = lambda: collections.defaultdict(_trie) trie = _trie() END = True for root in roots: cur = trie for letter in root: cur = cur[letter] cur[END] = root
defreplace(word): cur = trie for letter in word: if letter notin cur: break cur = cur[letter] if END in cur: return cur[END] return word
defaddWord(self, word): if word: cur = self.root for c in word: if c notin cur.children: cur.children[c] = TrieNode() cur = cur.children[c] cur.word = True
defgetRoot(self, word): ans = "" cur = self.root for c in word: if c in cur.children: ans += c cur = cur.children[c] if cur.word == True: # found smallest root! return ans else: break return word
trie = Trie() for word in roots: trie.addWord(word)
ans = [] for word in sentence.split(): ans.append(trie.getRoot(word)) return' '.join(ans)