题目:
单词数组 words 的 有效编码 由任意助记字符串 s 和下标数组 indices 组成,且满足:
words.length == indices.length
助记字符串 s 以 ‘#’ 字符结尾
对于每个下标 indices[i] ,s 的一个从 indices[i] 开始、到下一个 ‘#’ 字符结束(但不包括 ‘#’)的 子字符串 恰好与 words[i] 相等
给定一个单词数组 words ,返回成功对 words 进行编码的最小助记字符串 s 的长度 。
示例 1:
输入:words = [“time”, “me”, “bell”]
输出:10
解释:一组有效编码为 s = “time#bell#” 和 indices = [0, 2, 5] 。
words[0] = “time” ,s 开始于 indices[0] = 0 到下一个 ‘#’ 结束的子字符串,如加粗部分所示 “time#bell#”
words[1] = “me” ,s 开始于 indices[1] = 2 到下一个 ‘#’ 结束的子字符串,如加粗部分所示 “time#bell#”
words[2] = “bell” ,s 开始于 indices[2] = 5 到下一个 ‘#’ 结束的子字符串,如加粗部分所示 “time#bell#”
示例 2:
输入:words = [“t”]
输出:2
解释:一组有效编码为 s = “t#” 和 indices = [0] 。
提示:
1 <= words.length <= 2000
1 <= words[i].length <= 7
words[i] 仅由小写字母组成
注意:本题与主站 820 题相同: https://leetcode-cn.com/problems/short-encoding-of-words/
答案:
class Solution {
public class TrieNode{
boolean isEnd;
TrieNode[] next;
TrieNode(){
next = new TrieNode[26];
}
}
TrieNode root;
int sum = 0;
public int minimumLengthEncoding(String[] words) {
//注意这题是后缀树
//然后,字典树的叶子节点(没有孩子的节点)就代表没有后缀的单词,统计叶子节点代表的单词长度加一的和即为我们要的答案。
if(words.length == 0) return 0;
root = new TrieNode();
for(String str : words){
TrieNode node = root;
for(int i = str.length() - 1; i >= 0; i--){
if(node.next[str.charAt(i) - 'a'] == null){
node.next[str.charAt(i) - 'a'] = new TrieNode();
}
node = node.next[str.charAt(i) - 'a'];
}
node.isEnd = true;
}
dfs(root, 0);
return sum;
}
public void dfs(TrieNode root,int count){
for(int i = 0; i < 26; i++){
if(root.next[i] != null) {
root.isEnd = false;//如果不是叶子节点,则isEnd都设置为false;
dfs(root.next[i], count + 1);
}
}
if(root.isEnd == true) {
//System.out.println(count);
sum += (count + 1);
}
}
}