我有一个包含50,000到100,000个字符串的集合mystrings
。其中一些字符串可能是其他字符串的精确子字符串,我想将它们合并(丢弃子字符串并只保留最长的字符串)。目前我正在使用一种朴素的方法,其时间复杂度为O(N^2)
。
unique_strings = set()
for s in sorted(mystrings, key=len, reverse=True):
keep = True
for us in unique_strings:
if s in us:
keep = False
break
if keep:
unique_strings.add(s)
哪些数据结构或算法可以让这个任务更容易,而且不需要 O(N^2)
的操作。使用库是可以的,但我需要保持纯Python。
keep
布尔值,改用for
循环中的else
子句(当然不会改变时间复杂度)。http://python-notes.curiousefficiency.org/en/latest/python_concepts/break_else.html - Chris_Randsbreak
,只需将if keep:
替换为else:
(缩进相同),并删除所有带有keep
的行。当break
不发生时,才会执行else
子句。如果您不熟悉 for-else 结构,请阅读我上面链接的文章。 - Chris_Randsany()
或者all()
代替,像这样:if not any(s in us for us in unique_strings): unique_strings.add(s)
它会像break
一样短路。 - Chris_Rands