0x00 題幹
給定一個單詞列表,我們將這個列表編碼成一個索引字符串 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
每個單詞都是小寫字母 。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/short-encoding-of-words
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
0x01 題目分析
大致意思就是去除重複對字母,輸出編碼後對字符的長度,注意不要漏掉#號,後面的index表示的是尋找的字符串的起始位置。
如。time、me、bell,去重後就是time、bell,組合起來就是time#bell
0x02 題解
class Solution {
public int minimumLengthEncoding(String[] words) {
Set<String> wordsSet = new HashSet(Arrays.asList(words));
for (String word : words) {
for(int i = 1; i < word.length(); i++) {
wordsSet.remove(word.substring(i));
}
}
int count = 0;
for(String word : wordsSet) {
count += word.length() + 1;
}
return count;
}
}
大佬解法:
class Solution {
public int minimumLengthEncoding(String[] words) {
Node.code_len = 0;
Node root = new Node();
for (String w : words) {
Node.insert(root, w);
}
return Node.code_len;
}
static class Node {
static int code_len = 0;
Node[] children = new Node[26];
boolean isLeaf = false;
Node() {
}
static void insert(Node root, String s) {
Node p = root;
boolean add_falg = false;
for (int i = s.length()-1; i >=0; i--) {
char c = s.charAt(i);
int key = c - 'a';
if (p.isLeaf && i < s.length() - 1) {
code_len -= (s.length()-1-i) + 1;
p.isLeaf = false;
}
if (p.children[key] == null) {
p.children[key] = new Node();
add_falg = true;
}
p = p.children[key];
}
if (add_falg) {
code_len += s.length() + 1;
p.isLeaf = true;
}
}
}
}