leetcode 820. 单词的压缩编码

单词数组 words 的 有效编码 由任意助记字符串 s 和下标数组 indices 组成,且满足:

words.length == indices.length
助记字符串 s 以 '#' 字符结尾
对于每个下标 indices[i] ,s 的一个从 indices[i] 开始、到下一个 '#' 字符结束(但不包括 '#')的 子字符串 恰好与 words[i] 相等
给你一个单词数组 words ,返回成功对 words 进行编码的最小助记字符串 s 的长度 。

 

示例 1:

输入:words = ["time", "me", "bell"]
输出:10
解释:一组有效编码为 s = "time#bell#" 和 indices = [0, 2, 5] 。
words[0] = "time" ,s 开始于 indices[0] = 0 到下一个 '#' 结束的子字符串,如加粗部分所示 "time#bell#"
words[1] = "me" ,s 开始于 indices[1] = 2 到下一个 '#' 结束的子字符串,如加粗部分所示 "time#bell#"
words[2] = "bell" ,s 开始于 indices[2] = 5 到下一个 '#' 结束的子字符串,如加粗部分所示 "time#bell#"
示例 2:

输入:words = ["t"]
输出:2
解释:一组有效编码为 s = "t#" 和 indices = [0] 。
 

提示:

1 <= words.length <= 2000
1 <= words[i].length <= 7
words[i] 仅由小写字母组成

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

 

1:先把words中的字符都反转。

2:把words中的字符串排序。

3:从后往前遍历,若第i个字符串和 i + 1个字符串的前部分一样,则说明 i + 1覆盖了 i,则不用操作。

4:否则 计数器加上 i字符串的长度 ,再加上 1个 ‘#’的长度。

    public int minimumLengthEncoding(String[] words) {
        int length = words.length;
        for (int i = 0; i < length; i++) {
            words[i] = new StringBuilder(words[i]).reverse().toString();
        }
        Arrays.sort(words);
        int n = words[length - 1].length() + 1;
        for (int i = length - 2; i >= 0; i--) {
            String word = words[i];
            String word1 = words[i + 1];
            if (word.length() > word1.length()) {
                n = n + word.length() + 1;
            } else {
                if (!word.equals(words[i + 1].substring(0, word.length()))) {
                    n = n + word.length() + 1;
                }
            }
        }
        return n;
    }

leetcode 820. 单词的压缩编码

上一篇:LeetCode 387:字符串中的第一个唯一字符


下一篇:仿高德地图首页效果,简单代码实现