summary:
construct trie | traversal
package com.odyssey.app.algorithm.lc.trie;
import java.util.ArrayList;
import java.util.List;
/**
* 648
* medium
* https://leetcode.com/problems/replace-words/
*
* 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:
*
* Input: dict = ["cat", "bat", "rat"]
* sentence = "the cattle was rattled by the battery"
* Output: "the cat was rat by the bat"
*
*
* Note:
*
* The input will only have lower-case letters.
* 1 <= dict words number <= 1000
* 1 <= sentence words number <= 1000
* 1 <= root length <= 100
* 1 <= sentence words length <= 1000
*
*
* @author Dingsheng Huang
* @date 2020/3/27 21:15
*/
public class ReplaceWords {
class TrieNode {
TrieNode[] children = new TrieNode[26];
String word = "";
private void insert(TrieNode root, String word) {
char[] chs = word.toCharArray();
for (int i = 0; i < chs.length; i++) {
int idx = chs[i] - 'a';
if (root.children[idx] == null) {
root.children[idx] = new TrieNode();
}
root = root.children[idx];
}
root.word = word;
}
}
public String replaceWords(List<String> dict, String sentence) {
// construct trie
TrieNode root = new TrieNode();
for (String word : dict) {
root.insert(root, word);
}
// traverse every word in the sentence
String[] preset = sentence.split(" ");
List<String> result = new ArrayList<>();
for (String pre : preset) {
result.add(process(pre, root));
}
StringBuilder stringBuilder = new StringBuilder();
for (String item : result) {
stringBuilder.append(item);
stringBuilder.append(" ");
}
return stringBuilder.substring(0, stringBuilder.length() - 1);
}
private String process(String pre, TrieNode root) {
// just thinking when we should return result !!
char[] chs = pre.toCharArray();
for (int i = 0; i < chs.length; i++) {
int idx = chs[i] - 'a';
if (root.children[idx] == null) {
if (root.word.length() > 0) {
return root.word;
} else {
return pre;
}
}
if (root.children[idx].word.length() > 0) {
return root.children[idx].word;
}
root = root.children[idx];
}
if (root.word.length() > 0) {
return root.word;
} else {
return pre;
}
}
}