How to find all intersections (also called the longest common substrings) of two strings and their positions in both strings?
For example, if S1=\"never\"
This can be done in O(n+m) where n
and m
are lengths of input strings.
The pseudocode is:
function LCSubstr(S[1..m], T[1..n])
L := array(1..m, 1..n)
z := 0
ret := {}
for i := 1..m
for j := 1..n
if S[i] = T[j]
if i = 1 or j = 1
L[i,j] := 1
else
L[i,j] := L[i-1,j-1] + 1
if L[i,j] > z
z := L[i,j]
ret := {}
if L[i,j] = z
ret := ret ∪ {S[i-z+1..z]}
return ret
See the Longest_common_substring_problem wikipedia article for more details.