648. Replace Words
Problem
Replace every word of sentence that starts with one of the dictionary roots by the shortest such root; other words stay unchanged.
Example: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery" → "the cat was rat by the bat"
Insert the roots into a trie. For each word, walk the trie and stop at the first end-of-root marker; replace the word with that prefix.
Complexity: O(total characters).
class Solution:
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
root = {}
for w in dictionary:
node = root
for ch in w:
node = node.setdefault(ch, {})
node["$"] = True
def shortest(word):
node = root
for i, ch in enumerate(word):
if ch not in node:
return word
node = node[ch]
if "$" in node:
return word[:i + 1]
return word
return " ".join(shortest(w) for w in sentence.split())
assert Solution().replaceWords(["cat", "bat", "rat"], "the cattle was rattled by the battery") == "the cat was rat by the bat"
assert Solution().replaceWords(["a", "b", "c"], "aadsfasf absbs bbab cadsfafs") == "a a b c"
class Solution {
private static class Node { Node[] next = new Node[26]; boolean end; }
public String replaceWords(List<String> dictionary, String sentence) {
Node root = new Node();
for (String w : dictionary) {
Node n = root;
for (char c : w.toCharArray()) {
if (n.next[c - 'a'] == null) n.next[c - 'a'] = new Node();
n = n.next[c - 'a'];
}
n.end = true;
}
StringBuilder sb = new StringBuilder();
for (String w : sentence.split(" ")) {
if (sb.length() > 0) sb.append(' ');
Node n = root;
int i = 0;
for (; i < w.length() && n != null && !n.end; i++) n = n.next[w.charAt(i) - 'a'];
sb.append(n != null && n.end ? w.substring(0, i) : w);
}
return sb.toString();
}
}
func replaceWords(dictionary []string, sentence string) string {
type node struct {
next [26]*node
end bool
}
root := &node{}
for _, w := range dictionary {
n := root
for i := 0; i < len(w); i++ {
c := w[i] - 'a'
if n.next[c] == nil {
n.next[c] = &node{}
}
n = n.next[c]
}
n.end = true
}
shortest := func(word string) string { // the shortest root that prefixes word
n := root
for i := 0; i < len(word); i++ {
if n = n.next[word[i]-'a']; n == nil {
return word
}
if n.end {
return word[:i+1]
}
}
return word
}
words := strings.Fields(sentence)
for i, w := range words {
words[i] = shortest(w)
}
return strings.Join(words, " ")
}