首页 > 技术文章 > 单词的压缩编码

gongyanzh 2020-03-28 16:29 原文

820. 单词的压缩编码

给定一个单词列表,我们将这个列表编码成一个索引字符串 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] 。
#遍历,判断单词后缀是否在集合中出现过
def minimumLengthEncoding(words):
    if not words:
        return ""
    vocab = set(words)
    for word in words:
        #去掉后缀
        for i in range(1,len(word)):
            vocab.discard(word[i:])

    length = sum(len(w) for w in vocab)+len(vocab)
    return length
#字典树,后缀树,单词倒序插入
class Solution:
    def minimumLengthEncoding(self, words: List[str]) -> int:
        if not words:
            return 0
        root = {}
        is_end = -1
        length = 0
        #先从长倒短排序
        words.sort(key=lambda x:len(x),reverse=True)
        
        for word in words:
            curNode = root
            is_new = 0  
            for char in word[::-1]:#字典树,逆序插入
                if char not in curNode:#当前字符不存在,标记为新单词,创建新的节点
                    is_new = 1  #标记是新单词
                    curNode[char] = {}
                curNode = curNode[char]
            curNode[is_end] = True  #单词结尾
            length += len(word)+1 if is_new else 0  #如果是新单词长度+,否则不变
        return length

推荐阅读