LeetCode 648: Replace Words Solution
Master LeetCode problem 648 (Replace Words), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
648. Replace Words
Problem Explanation
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.
Solution Code
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();
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 648 (Replace Words)?
This page provides optimized solutions for LeetCode problem 648 (Replace Words) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 648 (Replace Words)?
The time complexity for LeetCode 648 (Replace Words) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 648 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 648 in Java, C++, or Python.