链接
题目描述
Trie前缀树
先把 words 数组中的字符串按长度从大到小排序,然后依次逆序插入 Trie 中
class Solution {
public int minimumLengthEncoding(String[] words) {
if(words == null || words.length == 0){
return 0;
}
Arrays.sort(words,(s1,s2)->s2.length()-s1.length());
Trie root = new Trie();
int res = 0;
for(int i = 0; i < words.length ;i++){
res += root.insert(words[i]);
}
return res;
}
class Trie{
TrieNode root;
public Trie(){
root = new TrieNode();
}
public int insert(String str){//逆序插入
char[] chars = str.toCharArray();
boolean isNew = false;
TrieNode cur = root;
for(int i = chars.length-1 ; i >= 0 ;i-- ){
if(cur.children[chars[i]-'a'] == null){
cur.children[chars[i]-'a'] = new TrieNode();
isNew = true;
}
cur = cur.children[chars[i]-'a'];
}
return isNew ? chars.length + 1 : 0;
}
}
class TrieNode{
char val;
TrieNode[] children = new TrieNode[26];
TrieNode(){}
}
}