题目描述
给定一个单词列表,我们将这个列表编码成一个索引字符串 S 与一个索引列表 A。
例如,如果这个列表是 [“time”, “me”, “bell”],我们就可以将其表示为 S = “time#bell#” 和 indexes = [0, 2, 5]。
对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 “#” 结束,来恢复我们之前的单词列表。
那么成功对给定单词列表进行编码的最小字符串长度是多少呢?
!只需要求最终编码的长度,不固定位置。
算法思路
1.0
使用字符串方法endswith。
class Solution(object):
def minimumLengthEncoding(self, words):
S_word=sorted(words,key=len,reverse=True)
l=[]
for word in S_word:
for i,j in enumerate(l):
if j.endswith(word):
break
else:
l.append(word)
return len('#'.join(l)+'#')
执行用时 :5428 ms, 在所有 Python 提交中击败了7.14%的用户
内存消耗 :13.4 MB, 在所有 Python 提交中击败了28.57%的用户
速度感人。
2.0
class Solution:
def minimumLengthEncoding(self, words):
words = sorted(words, key = lambda i: len(i), reverse=True)
s = ""
for i in words:
if i+"#" in s:continue
s += i+"#"
return len(s)
执行用时 :340 ms, 在所有 Python 提交中击败了18.57%的用户
3.0
排序。
class Solution(object):
def minimumLengthEncoding(self, words):
S_word=sorted(i[::-1] for i in words)
idx=0
l=[]
while idx<len(S_word):
i=S_word[idx]
idx+=1
while idx<len(S_word) and S_word[idx].startswith(i):
i=S_word[idx]
idx+=1
l.append(i)
print(l)
return len('#'.join(l)+'#')
执行用时 :136 ms, 在所有 Python 提交中击败了40.00%的用户
内存消耗 :13.2 MB, 在所有 Python 提交中击败了28.57%的用户