友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
648. 单词替换
在英语中,我们有一个叫做 词根(root) 的概念,可以词根 后面 添加其他一些词组成另一个较长的单词——我们称这个词为 衍生词 (derivative)。例如,词根 help
,跟随着继承词 ful
,可以形成新的单词 helpful
。
现在,给定一个由许多词根组成的词典 dictionary
和一个用空格分隔单词形成的句子 sentence
。你需要将句子中的所有衍生词用词根替换掉。如果衍生词有许多可以形成它的 词根,则用最短的 词根 替换它。
你需要输出替换之后的句子。
示例 1:
输入:dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery" 输出:"the cat was rat by the bat"
示例 2:
输入:dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs" 输出:"a a b c"
提示:
-
1 <= dictionary.length <= 1000
-
1 <= dictionary[i].length <= 100
-
dictionary[i]
仅由小写字母组成。 -
1 <= sentence.length <= 106
-
sentence
仅由小写字母和空格组成。 -
sentence
中单词的总量在范围[1, 1000]
内。 -
sentence
中每个单词的长度在范围[1, 1000]
内。 -
sentence
中单词之间由一个空格隔开。 -
sentence
没有前导或尾随空格。
思路分析
前缀树!
将“字典”放到字典树中,然后将句子拆分成单词,在字典树中查找。
-
一刷
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2025-09-19 20:46:30
*/
public String replaceWords(List<String> dictionary, String sentence) {
Trie root = new Trie();
for (String word : dictionary) {
root.add(word);
}
String[] words = sentence.split(" ");
for (int i = 0; i < words.length; i++) {
words[i] = root.find(words[i]);
}
return String.join(" ", words);
}
public static class Trie {
Trie[] nodes = new Trie[26];
boolean end = false;
public void add(String word) {
Trie[] curr = nodes;
Trie trie = null;
for (char c : word.toCharArray()) {
int idx = c - 'a';
trie = curr[idx];
if (trie == null) {
curr[idx] = new Trie();
trie = curr[idx];
}
curr = trie.nodes;
}
trie.end = true;
}
public String find(String word) {
Trie[] curr = nodes;
StringBuilder sb = new StringBuilder();
for (char c : word.toCharArray()) {
int idx = c - 'a';
Trie trie = curr[idx];
if (trie == null) {
break;
}
sb.append(c);
if (trie.end) {
return sb.toString();
}
curr = trie.nodes;
}
return word;
}
}