单词的压缩编码

1、题目描述: 

  给定一个单词列表,我们将这个列表编码成一个索引字符串 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
每个单词都是小写字母 。

链接:https://leetcode-cn.com/problems/short-encoding-of-words

2、思路:

  先将单词词组存到set中,因为set自带去重功能,然后由于有些单词其实是其他单词的后缀,这些单词就可以作为重复单词,去除掉,因此我们一次拿到每个单词,遍历它后缀的所有可能性,再将后缀构成的单词从map中去掉。

3、代码:官方精妙的语句

class Solution {
    public int minimumLengthEncoding(String[] words) {
        Set<String> good = new HashSet(Arrays.asList(words));
        for (String word: words) {
            for (int k = 1; k < word.length(); ++k)
                good.remove(word.substring(k));
        }

        int ans = 0;
        for (String word: good)
            ans += word.length() + 1;
        return ans;
    }
}

猜你喜欢

转载自www.cnblogs.com/guoyu1/p/12416531.html