LeetCode 820. 单词的压缩编码 Short Encoding of Words

简介: LeetCode 820. 单词的压缩编码 Short Encoding of Words

LeetCode 820. 单词的压缩编码 Short Encoding of Words


Table of Contents

一、中文版

二、英文版

三、My answer

四、解题报告


一、中文版

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

每个单词都是小写字母 。

 

二、英文版

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 <= words.length <= 2000.
1 <= words[i].length <= 7.
Each word has only lowercase letters.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/short-encoding-of-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


三、My answer

本题采用 LeetCode 的官方题解,记录如下:
class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        good = set(words)
        for word in words:
            for k in range(1, len(word)):
                good.discard(word[k:])
        return sum(len(word) + 1 for word in good)
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/short-encoding-of-words/solution/dan-ci-de-ya-suo-bian-ma-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


四、解题报告

记录官方题解是因为代码特别 pythonic,值得学习。

比如 set 的discard() 函数:https://www.runoob.com/python3/ref-set-discard.html

解题思路动图如下:

相关文章
|
6天前
|
存储 算法 安全
【刷题】 leetcode 面试题 01.06 字符串压缩
来看效果: 非常好!!!过啦!!!
25 5
【刷题】 leetcode 面试题 01.06 字符串压缩
|
7月前
代码随想录 Day7 字符串1 LeetCode T344反转字符串 T541 反转字符串II 151翻转字符串的单词
代码随想录 Day7 字符串1 LeetCode T344反转字符串 T541 反转字符串II 151翻转字符串的单词
29 0
|
4月前
|
自然语言处理 Go
golang力扣leetcode 720.词典中最长的单词
golang力扣leetcode 720.词典中最长的单词
17 0
|
4月前
|
Go
golang力扣leetcode 139.单词拆分
golang力扣leetcode 139.单词拆分
19 0
|
9月前
|
存储
LeetCode-393 UTF-8编码验证
LeetCode-393 UTF-8编码验证
|
5月前
|
Java
557. 反转字符串中的单词 III --力扣 --JAVA
给定一个字符串 s ,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
30 0
|
5月前
|
存储 自然语言处理 算法
☆打卡算法☆LeetCode 211. 添加与搜索单词 - 数据结构设计 算法解析
☆打卡算法☆LeetCode 211. 添加与搜索单词 - 数据结构设计 算法解析
|
5月前
|
测试技术
每日一题 --- 力扣318----最大单词长度乘积
每日一题 --- 力扣318----最大单词长度乘积
|
5月前
剑指Offer LeetCode 面试题58 - I. 翻转单词顺序
剑指Offer LeetCode 面试题58 - I. 翻转单词顺序
23 0
|
6月前
|
算法
代码随想录算法训练营第八天 | LeetCode 344.反转字符串、541. 反转字符串II、剑指Offer 05.替换空格、151.翻转字符串里的单词、剑指Offer58-II.左旋转字符串
代码随想录算法训练营第八天 | LeetCode 344.反转字符串、541. 反转字符串II、剑指Offer 05.替换空格、151.翻转字符串里的单词、剑指Offer58-II.左旋转字符串
46 0