[Medium] 820. The word compression coding

820. The word compression coding


link

Title Description

Here Insert Picture Description

Trie prefix tree

First words in the string array descending order by length, followed by the reverse insertion 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(){}
    }
    
}
Published 55 original articles · won praise 1 · views 859

Guess you like

Origin blog.csdn.net/weixin_42469108/article/details/105159129