疯狂学习算法之算法刷题题解之 leetcode 820 单词的压缩编码 medium

0x00 题干

给定一个单词列表,我们将这个列表编码成一个索引字符串 S 与一个索引列表 A。

例如,如果这个列表是 [“time”, “me”, “bell”],我们就可以将其表示为 S = “time#bell#” 和 indexes = [0, 2, 5]。

对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 “#” 结束,来恢复我们之前的单词列表。

那么成功对给定单词列表进行编码的最小字符串长度是多少呢?

示例:

输入: words = ["time", "me", "bell"]
输出: 10
说明: S = "time#bell#" , indexes = [0, 2, 5] 。

提示:

1 <= words.length <= 2000
1 <= words[i].length <= 7
每个单词都是小写字母 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/short-encoding-of-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

0x01 题目分析

大致意思就是去除重复对字母,输出编码后对字符的长度,注意不要漏掉#号,后面的index表示的是寻找的字符串的起始位置。
如。time、me、bell,去重后就是time、bell,组合起来就是time#bell

0x02 题解
class Solution {
    public int minimumLengthEncoding(String[] words) {
        Set<String> wordsSet = new HashSet(Arrays.asList(words));
        for (String word : words) {
            for(int i = 1; i < word.length(); i++) {
                wordsSet.remove(word.substring(i));
            }
        }
        int count = 0;
        for(String word : wordsSet) {
            count += word.length() +  1;
        }
        return count;
    }
}

大佬解法:

class Solution {
 public int minimumLengthEncoding(String[] words) {
        Node.code_len = 0;
        Node root = new Node();
        for (String w : words) {
            Node.insert(root, w);
        }
        return  Node.code_len;

    }


static class Node {
        static int code_len = 0;
        Node[] children = new Node[26];
        boolean isLeaf = false;

        Node() {
        }

        static void insert(Node root, String s) {
            Node p = root;
            boolean add_falg = false;
            for (int i = s.length()-1; i >=0; i--) {
                char c = s.charAt(i);
                int key = c - 'a';
                if (p.isLeaf && i < s.length() - 1) {
                     code_len -= (s.length()-1-i) + 1;
                    p.isLeaf = false;
                }
                if (p.children[key] == null) {
                    p.children[key] = new Node();
                    add_falg = true;
                }
                p = p.children[key];
            }
            if (add_falg) {
                code_len += s.length() + 1;
                p.isLeaf = true;
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章