给定一个单词列表,我们将这个列表编码成一个索引字符串 S 与一个索引列表 A。
例如,如果这个列表是 ["time", "me", "bell"]
,我们就可以将其表示为 S = "time#bell#"
和 indexes = [0, 2, 5]
。
对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 “#” 结束,来恢复我们之前的单词列表。
那么成功对给定单词列表进行编码的最小字符串长度是多少呢?
示例:
输入: words = [“time”, “me”, “bell”]
输出: 10
说明: S = “time#bell#” , indexes = [0, 2, 5] 。
提示:
1 <= words.length <= 2000
1 <= words[i].length <= 7
每个单词都是小写字母 。
跟后缀相关,可以用set存储,然后遍历把后缀相同的去掉,最后遍历set集合,里面的单词就是我们要求的所有;
class Solution {
public int minimumLengthEncoding(String[] words) {
Set<String> set = new HashSet<>(Arrays.asList(words));
int ans = 0;
for(String s : words){
for(int i = 1;i < s.length(); i++){
set.remove(s.substring(i));
}
}
for(String s : set){
ans += s.length() + 1;
}
return ans;
}
}
字典树:
class Solution {
public int minimumLengthEncoding(String[] words) {
TrieNode trie = new TrieNode();
Map<TrieNode, Integer> nodes = new HashMap();
for(int i = 0; i < words.length; i++){
String s = words[i];
TrieNode cur = trie;
//倒序 插入字典序
for(int j = s.length()- 1; j >= 0; --j){
cur = cur.get(s.charAt(j));
}
nodes.put(cur,i);
}
int ans = 0;
for(TrieNode node : nodes.keySet()){
// 如果是叶子 节点,才计算长度
if(node.count == 0){
ans += words[nodes.get(node)].length() + 1;
}
}
return ans;
}
}
class TrieNode{
int count;//记录是否为叶子节点
TrieNode[] children;
TrieNode(){
count = 0;
children = new TrieNode[26];
}
public TrieNode get(char c){
if(children[c - 'a'] == null){
children[c - 'a'] = new TrieNode();
count ++;
}
return children[c - 'a'];
}
}