LeetCode 820. Short Encoding of Words - Java - Trie

Given a list of words, we may encode it by writing a reference string S and a list of indexes A.

For example, if the list of words is ["time", "me", "bell"], we can write it as S = "time#bell#" and indexes = [0, 2, 5].

Then for each index, we will recover the word by reading from the reference string from that index until we reach a "#" character.

What is the length of the shortest reference string S possible that encodes the given words?

Example:

Input: words = ["time", "me", "bell"]
Output: 10
Explanation: S = "time#bell#" and indexes = [0, 2, 5].

Note:

  • 1 <= words.length <= 2000.
  • 1 <= words[i].length <= 7.
  • Each word has only lowercase letters.

Java代碼

class Solution {
    public int minimumLengthEncoding(String[] words) {
        if (words.length == 1) {
            return words[0].length() + 1;
        }
        // 按照單詞長度降序排序
        Arrays.sort(words, (o1, o2) -> {
            int len1 = o1.length();
            int len2 = o2.length();
            return (len1 < len2) ? 1 : ((len1 == len2) ? 0 : -1);
        });
        TrieNode root = new TrieNode();
        int result = 0;
        for (int i = 0; i < words.length; ++i) {
            result += insert(words[i], root);
        }
        return result;
    }

    private int insert(String word, TrieNode root) {
        TrieNode trieNode = root;
        boolean newWord = false;
        char[] chars = word.toCharArray();
        for (int j = chars.length - 1; j >= 0; --j) {
            int v = chars[j] - 'a';
            if (trieNode.children[v] == null) {
                newWord = true;
                trieNode.children[v] = new TrieNode();
            }
            trieNode = trieNode.children[v];
        }
        return newWord ? (chars.length + 1) : 0;
    }

    private class TrieNode {
        TrieNode[] children = new TrieNode[26];
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章