You are given a dictionary consisting of many roots and a sentence. You need to replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root with the shortest length.
dictionary = ["cat","bat","rat"]
sentence = "the cattle was rattled by the battery"
"the cat was rat by the bat"
dictionary = ["a", "b", "c"]
sentence = "aadsfasf absbs bbab cadsfafs"
"a a b c"
dictionary = ["a", "aa", "aaa", "aaaa"]
sentence = "a aa a aaaa aaa aaa aaa aaaaaa bbb baba ababa"
"a a a a a a a a bbb baba a"
import java.util.*;
class Solution {
// Trie Node
class TrieNode {
Map<Character, TrieNode> children;
boolean isEndOfWord;
public TrieNode() {
children = new HashMap<>();
isEndOfWord = false;
}
}
private TrieNode root;
// Initialize the Trie
public Solution() {
root = new TrieNode();
}
// Insert a word into the Trie
private void insert(String word) {
TrieNode current = root;
for (char ch : word.toCharArray()) {
current.children.putIfAbsent(ch, new TrieNode());
current = current.children.get(ch);
}
current.isEndOfWord = true;
}
// Search for the shortest root in the Trie
private String searchRoot(String word) {
TrieNode current = root;
StringBuilder sb = new StringBuilder();
for (char ch : word.toCharArray()) {
if (!current.children.containsKey(ch)) break;
sb.append(ch);
current = current.children.get(ch);
if (current.isEndOfWord) return sb.toString();
}
return word;
}
public String replaceWords(List<String> dictionary, String sentence) {
// Insert all dictionary roots into the Trie
for (String root : dictionary) {
insert(root);
}
// Split the sentence into words
String[] words = sentence.split(" ");
// Build the replaced sentence
StringBuilder replacedSentence = new StringBuilder();
for (String word : words) {
if (replacedSentence.length() > 0) replacedSentence.append(" ");
replacedSentence.append(searchRoot(word));
}
return replacedSentence.toString();
}
}
This implementation allows for efficient querying and replacement of words in the sentence using the provided dictionary.
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?