Python - how to find all intersections of two strings?

前端 未结 6 1694
花落未央
花落未央 2021-02-04 18:21

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\"

6条回答
  •  梦毁少年i
    2021-02-04 18:54

    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.

提交回复
热议问题