Skip to main content
added 44 characters in body
Source Link
Sphinx
  • 10.7k
  • 2
  • 35
  • 50

PS: You can try other algorithms also. And @Pault 's answers is good enough unless you care about the performance a lot.

PS: You can try other algorithms also. And @Pault 's answers is good enough unless you care about the performance a lot.

added 220 characters in body
Source Link
Sphinx
  • 10.7k
  • 2
  • 35
  • 50

I considered this question was like one substring search, so KMPKMP, BPBM etc sub-string algorithmsub-string search algorithm could be applied at here. Even you'd like support multiple patterns, there are some multiple pattern algorithms like Aho-Corasick, Wu-Manber etc.

Then use it to calcuate out the matched position, finally remove the match:

I considered this question was like one substring search, so KMP, BP etc sub-string algorithm could be applied at here.

Then use it to calcuate out the matched position:

I considered this question was like one substring search, so KMP, BM etc sub-string search algorithm could be applied at here. Even you'd like support multiple patterns, there are some multiple pattern algorithms like Aho-Corasick, Wu-Manber etc.

Then use it to calcuate out the matched position, finally remove the match:

Source Link
Sphinx
  • 10.7k
  • 2
  • 35
  • 50

I considered this question was like one substring search, so KMP, BP etc sub-string algorithm could be applied at here.

Below is KMP algorithm implemented by Python which is from GitHub Gist. PS: the author is not me. I just want to share my idea.

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 

Then use it to calcuate out the matched position:

A = [1, 2, 3, 4, 5, 6, 7, 7, 7, 3, 4] B = [3, 4] result = KMP().search(A, B) print(result) #assuming at least one match is found print(A[:result[0]:] + A[result[0]+len(B):]) 

Output:

[2, 9] [1, 2, 5, 6, 7, 7, 7, 3, 4] [Finished in 0.201s]