avatar

Catalog
单词的压缩编码

题目描述

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

解题思路

通过判断单词的后缀是否在集合中,在就去掉
知识点:
Set 函数discard 用于去掉集合中的值

代码

Code
1
2
3
4
5
6
7
8
9
10
class Solution:
def minimumLengthEncoding(self, words: List[str]) -> int:
if not words:
return 0
nss = set(words)
for w in words:
for i in range(1, len(w)):
nss.discard(w[i:])
return sum([len(w)+1 for w in nss])
Author: kim yhow
Link: http://yoursite.com/2020/03/28/820-单词的压缩编码/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
    微信
  • 支付寶
    支付寶