当前位置 博文首页 > CHEN_SN的博客:LeetCode820.单词的压缩编码——刷题日志
本人为小白,文章为日后复现,请谨慎参考。
给定一个单词列表,我们将这个列表编码成一个索引字符串 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
每个单词都是小写字母 。
首先我们应该看清楚题目
对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 “#” 结束,来恢复我们之前的单词列表。
这句话很关键,从S索引位置开始直到直到 “#” 结束
如图:
图片来源:甜姨
所以我们可以采用***字典树/Trie树/前缀树***的思想来解题。同时因为这题是比较后缀,所以将单词倒序插入,这样子就可以转化为前缀树进行比较。
图片来源:甜姨
public static int minimumLengthEncoding(String[] words) {
int len=0;
Trie trie=new Trie();
Arrays.sort(words, (s1, s2) -> s2.length() - s1.length());
for (String word: words) {
len+= trie.insert(word);
}
return len;
}
class TrieNode{
char val;
TrieNode [] children=new TrieNode[26];
public TrieNode(){}
}
class Trie{
TrieNode root;
public Trie(){
root=new TrieNode();
}
public int insert(String word){
TrieNode cur=root;
boolean f=false;
for(int i=word.length()-1;i>=0;i--){
int c=word.charAt(i)-'a';
if(cur.children[c]==null){
f=true;
cur.children[c]=new TrieNode();
}
cur=cur.children[c];
}
return f?word.length()+1:0;
}
}
创建前缀树,那么我们就需要先定义节点类,一个节点会与26个节点相连。如下:
class TrieNode{
char val;
TrieNode [] children=new TrieNode[26];
public TrieNode(){}
}
然后我们需要定义插入字符串的算法。我们需要将字符串反转,然后一个个取出字符,根据字符串长度循环,每一循环只需要判断其是已经存在节点,如果不存在,只需要创建(实例化节点)即可,这也意味着,这是一个新的单词。最后如果是新单词要+1(因为#),如果不是新单词返回0。
当然要创建树结构,那么当然在初始化的时候,需要新建一个根root,所以需要设置内部变量root和构造方法给root节点。
class Trie{
TrieNode root;
public Trie(){
root=new TrieNode();
}
public int insert(String word){
TrieNode cur=root;
boolean f=false;
for(int i=word.length()-1;i>=0;i--){
int c=word.charAt(i)-'a';
if(cur.children[c]==null){
f=true;
cur.children[c]=new TrieNode();
}
cur=cur.children[c];
}
return f?word.length()+1:0;
}
}
所以主函数只需要将字符串从大到小排序,然后一次次调用insert方法即可。
public static int minimumLengthEncoding(String[] words) {
int len=0;
Trie trie=new Trie();
Arrays.sort(words, (s1, s2) -> s2.length() - s1.length());
for (String word: words) {
len+= trie.insert(word);
}
return len;
}
cs