所以我有一个堆栈和针头:
堆栈 = 'lllolollololollllolol'
针头 = 'lol'
如果每次从堆栈中删除一个针头,并按正确的顺序进行,堆栈最终可以被清空,使其为空。例如,每次都会删除粗体中的'lol'(注意,在删除后可能会创建另一个针头): lllolollololollllolol lllolollolololllol lllolollolololl llollolololl llollolol llolol lol 清空
为了找到像上面那样的路径,我唯一想到的使用Python的方法是使用正则表达式(finditer)在堆栈中查找所有的针头,并使用递归来探索所有可能的删除组合,以找到可以使堆栈为空的组合。但我知道这样做效率不高。
是否有更有效的方法使用Python找到至少一种方法将针头移除以清空堆栈?
我发现了这个主题: Remove occurences of substring recursively 但我不确定它是否完全适用于我的情况。
谢谢!
以下是我想出的代码(复杂度很差,我知道...):
堆栈 = 'lllolollololollllolol'
针头 = 'lol'
如果每次从堆栈中删除一个针头,并按正确的顺序进行,堆栈最终可以被清空,使其为空。例如,每次都会删除粗体中的'lol'(注意,在删除后可能会创建另一个针头): lllolollololollllolol lllolollolololllol lllolollolololl llollolololl llollolol llolol lol 清空
为了找到像上面那样的路径,我唯一想到的使用Python的方法是使用正则表达式(finditer)在堆栈中查找所有的针头,并使用递归来探索所有可能的删除组合,以找到可以使堆栈为空的组合。但我知道这样做效率不高。
是否有更有效的方法使用Python找到至少一种方法将针头移除以清空堆栈?
我发现了这个主题: Remove occurences of substring recursively 但我不确定它是否完全适用于我的情况。
谢谢!
以下是我想出的代码(复杂度很差,我知道...):
def answer(chunk, word):
if chunk.find(word) != -1:
occ = [m.start() for m in finditer('(?='+word+')', chunk)]
for o in occ:
new = chunk[:o] + chunk[o + len(word):]
answer(new, word)
else:
result.append(chunk)
result.sort()
return chunk
...
#So all the shortest "leftover stack" after the removal are stored in list
#"result". These include empty or non-empty outputs depending on how
#the removal was executed.