LeetCode 820 Short Encoding of Words

20 篇文章 0 订阅
5 篇文章 0 订阅

LeetCode 820 Short Encoding of Words

传送门

题目分析

Given a list of words, we may encode it by writing a reference string S and a list of indexes A.

For example, if the list of words is ["time", "me", "bell"], we can write it as S = "time#bell#" and indexes = [0, 2, 5].

Then for each index, we will recover the word by reading from the reference string from that index until we reach a “#” character.

What is the length of the shortest reference string S possible that encodes the given words?

Example:

Input: words = ["time", "me", "bell"]
Output: 10
Explanation: S = "time#bell#" and indexes = [0, 2, 5].

Note:

  1. 1 <= words.length <= 2000.
  2. 1 <= words[i].length <= 7.
  3. Each word has only lowercase letters.

题目有点难理解,不过看了例子之后还是很快理解了题目的意思,就是将一堆单词编码为一个字符串,使用给定的例子说明一下:

String[] words = {"time", "me", "bell"};
String S = "time#bell#";
int[] indexes = {0, 2, 5};

metime的后缀,那么me就可以直接使用time表示,也即time#,对应的index就是2,而剩下的bell不是别的单词的后缀,也没有别的单词是bell的后缀,所以就是单独一个了。

再给一个示例

String[] words = {"time", "ti", "me"};
String S = "time#ti#";
int[] indexes = {0, 5, 2};

也很容易理解了吧。

题目要求的就是这个编码串的长度。

思考

我是用的暴力遍历所有字符串和其他字符串的关系,如果一个字符串是别的字符串的后缀那么就不需要将其添加到最终的字符串中,思路是没有错的,但是在第一次提交时得到了一个错误的提交,就是5个time字符串的编码,按照我的思路最终长度是0,然而是必须要有一个字符串的,那么就先对数据进行去重处理就可以了,再进行遍历,最终完美AC。

代码实现

import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;

class Solution {
    public int minimumLengthEncoding(String[] words) {
        if (words == null || words.length == 0) {
            return 1;
        }
        // 使用set对字符串去重
        HashSet<String> strings = new HashSet<>();
        // 添加数据,自动去重
        Collections.addAll(strings, words);

        Iterator<String> strs = strings.iterator();
        int size = 0;
        // 全部放入到原来的words中,其实新建一个大小为strings.size()的String数组是
        // 个更好的选择,为了时间不管了,运行中也没有报错。幸好没有要求给出对应的下标数组
        while (strs.hasNext()) {
            words[size++] = strs.next();
        }
        int result = 0, add;
        for (int i = 0; i < size; i++) {
            // 表示本字符串可以给最终字符串增加的长度
            add = words[i].length() + 1;
            for (int j = 0; j < size; j++) {
                // 如果这个字符串是别的字符串的后缀,那么这个字符串就可以用其表示
                // 而不需要在主串后再加一段
                if (i != j && words[j].endsWith(words[i])) {
                    add = 0;
                    break;
                }
            }

            result += add;
        }

        return result;
    }
}

感想

欢迎followGitHub

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值