这个问题已经在这里有了答案:????????????>????????????How to minimize a string’s length by iteratively removing all occurrences of some specified words from the string????????????????????????????????????2个
所以我有堆栈和针:
堆栈=’lllolollololollllolol’
针=’大声笑’
如果我每次以正确的顺序从堆栈中移出一根针,则可以清除堆栈,以便最后将其清空.
例如,每次都会删除黑体字的笑声(请注意,删除后可以进一步创建另一个针):
洛洛洛洛尔
洛洛洛洛尔洛洛尔
洛洛洛洛洛尔
洛洛洛洛尔
洛洛洛尔
洛洛尔
大声笑
明确
要找到上述路线,我想出的使用Python的唯一方法是使用正则表达式(finditer)查找堆栈中的所有指针,然后使用递归探索所有可能的删除组合以找到可以构成堆栈的组合空的.但是我知道这根本没有效率.
有没有一种更有效的方法来找到至少一种使用Python将针移到空堆栈的方法?
谢谢!
以下是我想出的代码(我知道很复杂):
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.