820. 单词的压缩编码
- 原题链接:
- 完成情况:
- 解题思路:
- 参考代码:
- __820单词的压缩编码__存储后缀
- __820单词的压缩编码__字典前缀树
原题链接:
820. 单词的压缩编码
https://leetcode.cn/problems/short-encoding-of-words/description/
完成情况:
解题思路:
/**
题目注解:
就是单词意思注解,
即:words = ["time", "me", "bell"]
想快速记忆,我们就可以用 s = "time#bell#" 和 indices = [0, 2, 5] 。
#代表,当前单词的结束,indices代表我开始读取单词的起始索引位置。
简单方法:
从头到尾计算,然后的话,就是当计算第一个的时候,如果当前单词又为后续单词的开头,那么我又可以再开一个索引号。
然后同时我还需要记住,构建的时候用#强制结尾,然后最后需要返回的只是我构建出来的模糊匹配的长度。
* @param words
* @return
*/
参考代码:
__820单词的压缩编码__存储后缀
package LeetCode中等题;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class __820单词的压缩编码__存储后缀 {
/**
题目注解:
就是单词意思注解,
即:words = ["time", "me", "bell"]
想快速记忆,我们就可以用 s = "time#bell#" 和 indices = [0, 2, 5] 。
#代表,当前单词的结束,indices代表我开始读取单词的起始索引位置。
简单方法:
从头到尾计算,然后的话,就是当计算第一个的时候,如果当前单词又为后续单词的开头,那么我又可以再开一个索引号。
然后同时我还需要记住,构建的时候用#强制结尾,然后最后需要返回的只是我构建出来的模糊匹配的长度。
* @param words
* @return
*/
public int minimumLengthEncoding(String[] words) {
//输入:words = ["time", "me", "bell"]
//构造一个去重Set集合childTab,避免掉重复单词,然后按顺序构成一个链表List
Set<String> childTab = new HashSet<String>(Arrays.asList(words));
for (String word:words){
for (int k=1;k< word.length();k++){
// 移出掉0-k
childTab.remove(word.substring(k));
}
}
int res = 0;
for (String word:childTab){
res+=word.length()+1;
}
return res;
}
}
__820单词的压缩编码__字典前缀树
package LeetCode中等题;
import java.util.HashMap;
import java.util.Map;
public class __820单词的压缩编码__字典前缀树 {
public int minimumLengthEncoding(String[] words) {
DictTrieNode dictTrie = new DictTrieNode();
Map<DictTrieNode,Integer> nodes = new HashMap<DictTrieNode,Integer>();
for (int i=0;i< words.length;i++){
String word = words[i];
//一个words里面的元素,作为一个单独的字典去进行计算,然后如果单词寻找的过程中,
//我发现如果有计算到重复元素的话,那么就可以给他单独再开一个位置去index出来。
DictTrieNode cur = dictTrie;
for (int j = word.length()-1;j>=0;j--){
cur = cur.getChildren(word.charAt(j));
}
nodes.put(cur,i);
}
int res = 0;
for (DictTrieNode node: nodes.keySet()){ // // 使用 keySet() 方法获取键的集合
if (node.count == 0){
res+=words[nodes.get(node)].length() + 1;
}
}
return res;
}
class DictTrieNode{ //就像前面提到的,字母一共就只有26个,那么你可以尝试选择构造一个包含有26个单词的数组去进行二叉树的遍历尝试。
DictTrieNode[] children;
int count;
DictTrieNode(){
children = new DictTrieNode[26];
count = 0;
}
public DictTrieNode getChildren(char c) {
if (children[c - 'a'] == null){
children[c - 'a'] = new DictTrieNode();
count++;
}
return children[c - 'a'];
}
}
}