Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Find the Longest Common Substring of Two Strings

Python Find the Longest Common Substring of Two Strings

Document Object Reference Manual Python3 Examples

The longest common substring problem is: given two strings, find the longest substring common to both. A substring is a contiguous sequence of characters within a string. We can solve this problem using dynamic programming.

Example

def

longest_common_substring

(

s1

,

s2

)

:

    m

=

len

(

s1

)

    n

=

len

(

s2

)

   

Create a 2D array to store the length of the longest common substring

    dp

=

[

[

0

]

(

n +

1

)

for

_

in

range

(

m +

1

)

]

    max_length

=

0

 

Record the length of the longest common substring

    end_pos

=

0

   

Record the ending position of the longest common substring

   

for

i

in

range

(

1

,

m +

1

)

:

       

for

j

in

range

(

1

,

n +

1

)

:

           

if

s1

[

i -

1

]

==

s2

[

j -

1

]

:

                dp

[

i

]

[

j

]

=

dp

[

i -

1

]

[

j -

1

]

1

               

if

dp

[

i

]

[

j

]

max_length:

                    max_length

=

dp

[

i

]

[

j

]

                    end_pos

=

i

           

else

:

                dp

[

i

]

[

j

]

=

0

   

Return the longest common substring

   

return

s1

[

end_pos - max_length:end_pos

]

Testing

s1

=

"abcdef"

s2

=

"zbcdf"

result

=

longest_common_substring

(

s1

,

s2

)

print

(

"The longest common substring is:"

,

result

)

Code analysis:

  1. dp is a 2D array,dp[i][j] represents the string s1 's first i characters and the string s2 's first j characters' longest common substring length.
  2. We iterate over each character of the two strings; if s1[i-1] and s2[j-1] are equal, then dp[i][j] 's value equals dp[i-1][j-1] + 1, otherwise dp[i][j] is 0.
  3. max_length is used to record the length of the longest common substring,end_pos is used to record the ending position of the longest common substring.
  4. Finally, we use s1[end_pos - max_length:end_pos] to obtain the longest common substring.

Output result:

最长公共子串是: bcd

Document Object Reference Manual Python3 Examples