648. Replace Words
Explanation
To solve this problem, we can follow these steps:
- Create a trie data structure to store all the roots from the dictionary.
- For each word in the sentence, check if it has a root in the trie.
- Replace the word with the shortest root if it has multiple roots.
- Return the modified sentence.
Time complexity: O(n * m) where n is the number of words in the sentence and m is the average length of a word. Space complexity: O(n * m) to store the trie.
class TrieNode {
Map<Character, TrieNode> children;
boolean isEndOfWord;
TrieNode() {
children = new HashMap<>();
isEndOfWord = false;
}
}
class Trie {
TrieNode root;
Trie() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
node.children.putIfAbsent(c, new TrieNode());
node = node.children.get(c);
}
node.isEndOfWord = true;
}
public String searchRoot(String word) {
TrieNode node = root;
StringBuilder rootWord = new StringBuilder();
for (char c : word.toCharArray()) {
if (!node.children.containsKey(c) || node.isEndOfWord) {
break;
}
rootWord.append(c);
node = node.children.get(c);
}
return node.isEndOfWord ? rootWord.toString() : word;
}
}
class Solution {
public String replaceWords(List<String> dictionary, String sentence) {
Trie trie = new Trie();
for (String root : dictionary) {
trie.insert(root);
}
StringBuilder result = new StringBuilder();
for (String word : sentence.split(" ")) {
result.append(trie.searchRoot(word)).append(" ");
}
return result.toString().trim();
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.