题目:leetcode820.单词的压缩编码
给定一个单词列表,我们将这个列表编码成一个索引字符串 S 与一个索引列表 A。
例如,如果这个列表是 ["time", "me", "bell"],我们就可以将其表示为 S = "time#bell#" 和 indexes = [0, 2, 5]。
对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 "#" 结束,来恢复我们之前的单词列表。
那么成功对给定单词列表进行编码的最小字符串长度是多少呢?
题意解析:若一个单词是另一个单词的后缀,那么这个单词就可以不用增加到索引字符串S中。
知识储备trie树
这里用到字典树来解题。
class Solution {
//定义trie字典树结点
class TrieNode {
public char val;
TrieNode[] children = new TrieNode[26];
public TrieNode() {}
public TrieNode(char val) {
this.val = val;
}
}
public int minimumLengthEncoding(String[] words) {
TrieNode root = new TrieNode();
int ans = 0;
//先长后短,防止 先短后长导致的误判为有两个新单词
Arrays.sort(words, (a,b)->(b.length() - a.length()));
for(String word : words) {
ans += insert(word, root);
}
return ans;
}
private int insert(String word, TrieNode root) {
//标记是否为新单词
boolean isNew = false;
//逆序,寻找相同后缀的单词
for(int i = word.length() - 1; i >= 0; i--) {
char c = word.charAt(i);
if(root.children[c - 'a'] == null) {
isNew = true;
root.children[c - 'a'] = new TrieNode(c);
}
root = root.children[c - 'a'];
}
//是新单词添加到S字符串的同时加一个#号,所以再加1
return isNew ? word.length() + 1 : 0;
}
}