【发布时间】:2011-08-25 04:39:35
【问题描述】:
给你一个字符串和一个字符串数组。如何快速检查这个字符串是否可以通过连接数组中的一些字符串来构建?
这是一个理论问题,出于实际原因我不需要它。但我想知道,是否有一些好的算法。
编辑 阅读一些我注意到的答案,这可能是 NP-Complete 问题。即使找到一个字符串子集,它们的长度也相同,因为给定的字符串是一个经典的子集求和问题。
所以我想这个问题没有简单的答案。
编辑
现在看来,这毕竟不是一个 NP 完全问题。那就更酷了:-)
编辑
我想出了一个通过一些测试的解决方案:
def can_build_from_substrings(string, substrings):
prefixes = [True] + [False] * (len(string) - 1)
while True:
old = list(prefixes)
for s in substrings:
for index, is_set in enumerate(prefixes):
if is_set and string[index:].startswith(s):
if string[index:] == s:
return True
prefixes[index + len(s)] = True
if old == prefixes: # nothing has changed in this iteration
return False
我相信时间是O(n * m^3),其中n 的长度为substrings,m 的长度为string。你怎么看?
【问题讨论】:
-
感觉像是背包问题的变种。
-
你可以只使用数组中的字符串一次吗?
标签: algorithm string substring