Java implementation LeetCode compression coding (trie) 820 words

820. The word compression coding

Given a list of words, this list will be encoded as a string S index and an index list A.

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

For each index, we can start by reading the string index from the string S in position until the "#" end, to restore our previous list of words.

Then the minimum length of the string to the success of a given word list for encoding is how much?

Example:

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

prompt:

. 1 <= words.length <= 2000
. 1 <= words [I] .length <=. 7
each word lowercase.

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() {}
}
Released 1653 original articles · won praise 20000 + · views 3.01 million +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/105157256