原题
给定一个单词列表,我们将这个列表编码成一个索引字符串 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
- 每个单词都是小写字母 。
解法
思想
- 暴力搜索后缀。
-
使用字典树倒序存储字符串。
代码
暴力检查后缀:
class Solution {
public int minimumLengthEncoding(String[] words) {
List<String> list = new ArrayList<>();
for(String word:words){
boolean noNeedToAdd = false;
for(int i = 0;i<list.size();i++){
if(word.lastIndexOf(list.get(i))!=-1&&word.lastIndexOf(list.get(i))==word.length()-list.get(i).length()){
list.set(i,word);
noNeedToAdd = true;
}else if(list.get(i).lastIndexOf(word)!=-1&&list.get(i).lastIndexOf(word)==list.get(i).length()-word.length()){
noNeedToAdd = true;
}
}
if(!noNeedToAdd) list.add(word);
}
int sum = 0;
for(String word:list){
sum += word.length()+1;
}
return sum;
}
}
使用字典树倒序存储字符串:
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 word = words[i];
TrieNode cur = trie;
for (int j = word.length() - 1; j >= 0; --j)
cur = cur.get(word.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 {
TrieNode[] children;
int count;
TrieNode() {
children = new TrieNode[26];
count = 0;
}
public TrieNode get(char c) {
if (children[c - 'a'] == null) {
children[c - 'a'] = new TrieNode();
count++;
}
return children[c - 'a'];
}
}
原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode820-%e5%8d%95%e8%af%8d%e7%9a%84%e5%8e%8b%e7%bc%a9%e7%bc%96%e7%a0%81/