820. 单词的压缩编码

class Solution {
    private TrieNode root = new TrieNode();
    public int minimumLengthEncoding(String[] words) {
        int res = 0;
        Arrays.sort(words,(o1,o2)->o2.length()-o1.length());// 需要排序先插入长的
        for(String s : words) {
            res += insert(s);
        }
        return res;
    }
    public int insert(String s) {
        TrieNode node = root;
        boolean f = false;
        for(int i = s.length() - 1; i > -1; i--) {
            char c = s.charAt(i);
            if(node.children[c-'a'] == null) {
                f = true;
                node.children[c-'a'] = new TrieNode(c);
            }
            node = node.children[c-'a'];
        }
        if(f) return s.length()+1; // 是新单词就全部加入并在结尾加上'#'
        else return 0; // 不是新单词就不用加
    }
}
class TrieNode {
    char c;
    TrieNode[] children = new TrieNode[26];
    public TrieNode(){}
    public TrieNode (char c) {
        this.c = c;
    }
}

 

posted @ 2020-09-15 10:51  Sexyomaru  阅读(165)  评论(0编辑  收藏  举报