1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution { public int minimumLengthEncoding(String[] words) { Trie trie = new Trie(); int len = 0; Arrays.sort(words, (s1, s2) -> s2.length() - s1.length()); for (String s : words) { len += trie.insert(s); } return len; }
class TrieNode { char val; TrieNode[] children = new TrieNode[26]; }
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; } } }
|