这几天的打卡

来晚啦
有几天题目过于简单就没写博客了,今这题就写一篇吧
先来一题今天晚上的
820. 单词的压缩编码
这几天的打卡_第1张图片
这题有点骚,首先排除暴力解。
用字典树,这里是需要先排序再倒叙插入字典树,具体原因自己看一下就很明白了,正着是无法判断后缀问题的,那如果me在前time在后,那time还得再插一遍,所以我们将长的字符串放在前面,避免这种情况.

class Solution {
    public class lenSort implements Comparator<String>{
        public int compare(String s1, String s2) {
            return s2.length()- s1.length();
        }
    }
    public int minimumLengthEncoding(String[] words) {
        Arrays.sort(words, new lenSort());
        Trie Trietree = new Trie();
        StringBuilder sb = new StringBuilder();
        for(String i : words) {
            StringBuilder t = new StringBuilder(i);
            t = t.reverse();
            if(!Trietree.contain(t.toString())) {
                Trietree.add(t.toString());
                sb.append(i);
                sb.append("#");
            }
        }
        return sb.length();
    }

    public class Trie {
        TreeNode root;
        public Trie() {
            root = new TreeNode();
        }
        public void add(String s) {
            char[] ch = s.toCharArray();
            TreeNode cur = root;
            int index = 0;
            for(int i = 0; i < ch.length; i ++) {
                index = ch[i] - 'a';
                if(cur.dict[index] == null) {
                    cur.dict[index] = new TreeNode();
                }
                cur = cur.dict[index];
            }
            cur.isEnd = true;
            return ;
        }

        public boolean contain(String s) {
            char[] ch = s.toCharArray();
            TreeNode cur = root;
            int index = 0;
            for(int i = 0; i < ch.length; i ++) {
                index = ch[i] - 'a';
                if(cur.dict[index] == null) {
                    return false;
                }
                cur = cur.dict[index];
            }
            return true;
        }
    }

    public class TreeNode {
        public TreeNode[] dict;
        public boolean isEnd;

        public TreeNode() {
            this.dict = new TreeNode[26];
            this.isEnd = false;
        }
    }
}

你可能感兴趣的:(leetcode)