820単語圧縮コーディング
単語のリストを考えると、このリストには、文字列SインデックスとインデックスリストAとしてエンコードされます
例えば、リストが[ "時間"、 "私"、 "ベル"]、我々は、S = "タイム#ベル#" とインデックス= [0、2、5]のように表すことができます。
各インデックスのために、私たちは言葉の私達の前のリストを復元するには、「#」終了までの位置にある文字列Sから文字列のインデックスを読むことによって開始することができます。
そして、エンコーディングのための与えられた単語リストを成功させるために、文字列の最小の長さはどのくらいですか?
例:
入力:言葉= [ "時間"、 "私"、 "ベル"]
出力:10
説明:S = "時間#ベル# "、インデックス= [0、2、5]。
ヒント:
1 <= words.length <= 2000
。1 <=ワード[I] .LENGTH <= 7
各ワード小文字。
class Solution {
public 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;
}
}
// 定义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];
}
return isNew? word.length() + 1: 0;
}
}
class TrieNode {
char val;
TrieNode[] children = new TrieNode[26];
public TrieNode() {}
}