我认为这个问题就像一个子字符串搜索,因此可以应用
子字符串搜索算法,如
KMP、
BM等。即使您想支持多个模式,也有一些多模式算法,如
Aho-Corasick、
Wu-Manber等。
下面是来自GitHub Gist的Python实现的KMP算法。
注:作者不是我。我只是想分享我的想法。
class KMP:
def partial(self, pattern):
""" Calculate partial match table: String -> [Int]"""
ret = [0]
for i in range(1, len(pattern)):
j = ret[i - 1]
while j > 0 and pattern[j] != pattern[i]:
j = ret[j - 1]
ret.append(j + 1 if pattern[j] == pattern[i] else j)
return ret
def search(self, T, P):
"""
KMP search main algorithm: String -> String -> [Int]
Return all the matching position of pattern string P in S
"""
partial, ret, j = self.partial(P), [], 0
for i in range(len(T)):
while j > 0 and T[i] != P[j]:
j = partial[j - 1]
if T[i] == P[j]: j += 1
if j == len(P):
ret.append(i - (j - 1))
j = 0
return ret
然后使用它来计算出匹配的位置,最后移除匹配:
A = [1, 2, 3, 4, 5, 6, 7, 7, 7, 3, 4]
B = [3, 4]
result = KMP().search(A, B)
print(result)
print(A[:result[0]:] + A[result[0]+len(B):])
输出:
[2, 9]
[1, 2, 5, 6, 7, 7, 7, 3, 4]
[Finished in 0.201s]
附注:您也可以尝试其他算法。@Pault的答案足够好,除非您非常关心性能。
A - B
。 - NetwaveA = [1, 2, 3, 4, 5, 6, 7, 3, 8, 5, 4]
,输出是什么? - pault