算法记录
LeetCode 题目:
在英语中,有一个叫做词根(root) 的概念,它可以跟着其他一些词组成另一个较长的单词——我们称这个词为继承词(successor)。例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。
说明
一、题目
现在,给定一个由许多词根组成的词典和一个句子,需要将句子中的所有继承词用词根替换掉。如果继承词有许多可以形成它的词根,则用最短的词根替换它。需要输出替换之后的句子。
二、分析
- 从题意中判断,两个单词可合成一个新的单词,而给出的句子是已经合成的单词,我们仅需要找出这个单词在合成前的前缀即可;
- 求前缀恰好就回到了前缀树的使用上来,先用给定的字典构建一个字典树,然后将给出的句子进行拆分之后匹配,前缀树中存在此单词的前缀即马上输出,否则输出原单词。
class Solution {
public String replaceWords(List<String> dictionary, String sentence) {
Node head = new Node();
for(String s : dictionary) head.insert(s);
String[] words = sentence.split(" ");
StringBuilder builder = new StringBuilder();
for(String s : words) {
builder.append(" " + head.search(s));
}
return builder.toString().substring(1);
}
}
class Node{
public boolean flag;
public Node[] next;
public Node() {
flag = false;
next = new Node[26];
}
public void insert(String s) {
Node temp = this;
for(char c : s.toCharArray()) {
if(temp.next[c - 'a'] == null) temp.next[c - 'a'] = new Node();
temp = temp.next[c - 'a'];
}
temp.flag = true;
}
public String search(String s) {
Node temp = this;
char[] words = s.toCharArray();
for(int i = 0; i < s.length(); i++) {
if(temp == null) return s;
if(temp.flag) return s.substring(0, i);
temp = temp.next[words[i] - 'a'];
}
return s;
}
}
总结
熟悉前缀树的特点。