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
代码精妙之处:
- 首先就是对于尾缀题目的思路,遇事不决先排序的思路不错。排序之后只需要检测前一项和后一项的尾缀是否一致就可。
- 匿名函数的使用。这次是用在了排序上,不改变原列表的基础上按照尾缀的次序进行排序。
关于前缀树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