题目描述:
你需要输出替换之后的句子。
示例 1:
输入: dict(词典) = [“cat”, “bat”, “rat”]
sentence(句子) = “the cattle was rattled by the battery”
输出: “the cat was rat by the bat”
注:
输入只包含小写字母。
1 <= 字典单词数 <=1000
1 <= 句中词语数 <= 1000
1 <= 词根长度 <= 100
1 <= 句中词语长度 <= 1000
首先我们能想到的就是使用前缀树,新建一个类,用于表示每个节点,子孩子为一个数组,表示的是26个字母
代码:
class Solution {
// 2019年7月24日08:55:43
Mytree root = new Mytree();
public String replaceWords(List<String> dict, String sentence) {
adddict(dict);
StringBuilder sBuilder = new StringBuilder();
for (String string : sentence.split(" ")) {
int index = search(string);
String str = index > 0 ? string.substring(0,index):string;
sBuilder.append(str).append(" ");
}
return new String(sBuilder).substring(0, sBuilder.length() - 1);
}
public int search(String tem){
Mytree node = root;
int index = 0;
for (char i : tem.toCharArray()) {
if(node.child[i - 'a'] == null && !node.isend){
return 0;
}
if(node.isend)
return index;
index ++;
node = node.child[i - 'a'];
}
return index;
}
public void adddict(List<String> dict){
for (String string : dict) {
Mytree get = root;
for (char c : string.toCharArray()) {
if(get.child[c - 'a'] == null){
get.child[c - 'a'] = new Mytree();
}
get = get.child[c - 'a'];
}
get.isend = true;
}
}
}
class Mytree{
boolean isend;
Mytree child[] = new Mytree[26];
}