- 单词的压缩编码
给定一个单词列表,我们将这个列表编码成一个索引字符串 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
每个单词都是小写字母 。
class Solution(object):
def minimumLengthEncoding(self, words):
"""
:type words: List[str]
:rtype: int
"""
words = sorted(w[::-1] for w in words)
res = [len(words[0])]#此时res只有一个元素,位倒数第一个翻转字符串的长度。
for i in range(1, len(words)):
if words[i].startswith(words[i - 1]): # 前一个被它包含
res[-1] = len(words[i]) # 则用新的这个替换前一个作为之前几个被包含项的的索引字符串
else: # 前一个不能被其包含
res.append(len(words[i])) # 新增一个字符串用来索引
return sum(res) + len(res) # len(res)是'#'的个数
# 突破点:因为只能通过'#'来表示单词的结束,所以如果某个单词能通过包含它的单词来索引,那么它只能出现在那个单词的最后
# 因此可以通过将每个词翻转并排序后循环处理