我正在研究一个问题,即必须确定字符串是否是其他字符串的串联(这些字符串可以在连接的字符串中重复)。我正在使用回溯来尽可能高效。如果字符串是串联,它将打印它是串联的字符串。如果没有,它将打印NOT POSSIBLE
。这是我的python代码:
# note: strList has to have been sorted
def findFirstSubstr(strList, substr, start = 0):
index = start
if (index >= len(strList)):
return -1
while (strList[index][:len(substr)] != substr):
index += 1
if (index >= len(strList)):
return -1
return index
def findPossibilities(stringConcat, stringList):
stringList.sort()
i = 0
index = 0
substr = ''
resultDeque = []
indexStack = []
while (i < len(stringConcat)):
substr += stringConcat[i]
index = findFirstSubstr(stringList, substr, index)
if (index < 0):
if (len(resultDeque) == 0):
return 'NOT POSSIBLE'
else:
i -= len(resultDeque.pop())
index = indexStack.pop() + 1
substr = ''
continue
elif (stringList[index] == substr):
resultDeque.append(stringList[index])
indexStack.append(index)
index = 0
substr = ''
i += 1
return ' '.join(resultDeque)
我一直在测试案例的后半部分失败,并且无法弄清楚原因。对于任何会失败的情况,有人会提示我正确的方向吗?谢谢!
答案 0 :(得分:1)
首先,这个代码是不必要的复杂。例如,这是一个等效但更短的解决方案:
def findPossibilities(stringConcat, stringList):
if not stringConcat: # if you want exact match, add `and not stringList`
return True
return any(findPossibilities(stringConcat[len(s):],
stringList[:i] + stringList[i+1:]) # assuming non-repeatable match. Otherwise, simply replace with `stringList`
for i, s in enumerate(stringList)
if stringConcat.startswith(s))
实际答案:
边境条件:stringConcat
的剩余部分与某些stringList
匹配,搜索停止:
>>> findPossibilities('aaaccbbbccc', ['aaa', 'bb', 'ccb', 'cccc'])
'aaa ccb bb'