【问题描述】
给定一个单词列表,我们将这个列表编码成一个索引字符串 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
每个单词都是小写字母 。
【解答思路】
1. 数组加入set中,切割set中每个单词后缀,剔除相同的后缀 (如切割time 剔除me)
- word.substring(n) -> 从第n个下标开始切割(n<word.length())
例子 - time.substring(1) -> ime
- time.substring(2) -> me
- time.substring(3) -> e
class Solution {
public int minimumLengthEncoding(String[] words) {
Set<String> set = new HashSet<>(Arrays.asList(words));
for (String word : words) {
for (int i = 1; i < word.length(); i++) {
set.remove(word.substring(i));
}
}
int ans = 0;
//+1 按照题意#
for (String word : set) {
ans += word.length() + 1;
}
return ans;
}
}
2. 字典树/Trie树/前缀树 O(N^2)
- 把单词的倒序插入字典树(后缀)长度越长优先插入
- 字典树判断某个单词的逆序是否出现在字典树里
class Solution {
public int minimumLengthEncoding(String[] words) {
int len = 0;
Trie trie = new Trie();
// 先对单词列表根据单词长度由长到短排序
Arrays.sort(words, (s1, s2) -> s2.length() - s1.length());
// 单词插入trie,返回该单词增加的编码长度
for (String word: words) {
len += trie.insert(word);
}
return len;
}
}
// 定义tire
class Trie {
TrieNode root;
public Trie() {
root = new TrieNode();
}
public int insert(String word) {
TrieNode cur = root;
boolean isNew = false;
// 倒着插入单词
for (int i = word.length() - 1; i >= 0; i--) {
int c = word.charAt(i) - 'a';
if (cur.children[c] == null) {
isNew = true; // 是新单词
cur.children[c] = new TrieNode();
}
cur = cur.children[c];
}
// 如果是新单词的话编码长度增加新单词的长度+1,否则不变。
return isNew? word.length() + 1: 0;
}
}
class TrieNode {
char val;
TrieNode[] children = new TrieNode[26];
public TrieNode() {}
}
作者:sweetiee
链接:https://leetcode-cn.com/problems/short-encoding-of-words/solution/99-java-trie-tu-xie-gong-lue-bao-jiao-bao-hui-by-s/
【总结】
- length 属性 length()方法
-java中数组是没有length()方法的,只有length属性,数组array.length返回的是该数组的长度。
-字符串String是有length()方法的,str.length()返回的是该字符串的长度。
2.字典树出现地方
- 搜索引擎 联想字段
- 区块链 以太坊 Merkle Patricia Tree 默克尔树+前缀树
- 英语分词