【每日一题】820 单词压缩编码

2020.3.28 题目难度: medium

在这里插入图片描述题目是字符串处理类。首次未做出。
思路分为两种,一种是使用排序的方法,检索单词的后缀是否相同。另外一种是采用字符树。
这里主要介绍排序的方法:

class Solution(object):
    def minimumLengthEncoding(self, words):
        """
        :type words: List[str]
        :rtype: int
        """
        words.sort(key = lambda x:x[::-1])
        res = 0
        for i in range(len(words)-1):
        	# 判断后一个字符是否以前一个字符为尾缀
        	if not words[i+1].endswith(words[i]):
        		res += len(words[i])+1
        return res+len(words[-1])+1

代码精妙之处:

  1. 首先就是对于尾缀题目的思路,遇事不决先排序的思路不错。排序之后只需要检测前一项和后一项的尾缀是否一致就可。
  2. 匿名函数的使用。这次是用在了排序上,不改变原列表的基础上按照尾缀的次序进行排序。

关于前缀树trie的我贴上树的结构:

class Tire:
    def __init__(self):
        self.dic ={}

    def insert(self, word):
        a = self.dic
        for x in word:
            if not x in a:
                a[x] = {}
            a = a[x]
        a['end'] = True

    def search(self, word):
        a = self.dic
        for x in word:
            if not x in a:
                return False
            a = a[x]
        if 'end' in a:
            return True

    def straswith(self, word):
        a = self.dic
        for x in word:
            if not x in a:
                return False
            a = a[x]
        return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值