Python Forum
Python implementation of Longest Common Substring problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python implementation of Longest Common Substring problem
#1
What is the longest common substring (LCS) of two strings?

The LCS of two strings is the longest sequence of characters that appears in both strings. For example, the LCS of the strings "ABCDGH" and "AEDFHR" is "ADH".

There are many ways to solve the longest common substring in Python. One common approach is to use a dynamic programming algorithm. The following Python code implements a dynamic programming algorithm for the LCS problem:

def lcs(s1, s2):
  n, m = len(s1), len(s2)
  dp = [[0 for _ in range(m + 1)] for _ in range(n + 1)]

  for i in range(1, n + 1):
    for j in range(1, m + 1):
      if s1[i - 1] == s2[j - 1]:
        dp[i][j] = dp[i - 1][j - 1] + 1
      else:
        dp[i][j] = max(dp[i][j - 1], dp[i - 1][j])

  return dp[n][m]


s1 = "ABCDGH"
s2 = "AEDFHR"

lcs = lcs(s1, s2)
print(lcs)
Output:

ADH

What is your preferred approach for solving the LCS problem? Is there a more efficient way to solve the problem?
Reply


Messages In This Thread
Python implementation of Longest Common Substring problem - by Bolt - Sep-17-2023, 08:31 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  extract substring from a string before a word !! evilcode1 3 589 Nov-08-2023, 12:18 AM
Last Post: evilcode1
  Python code for Longest Common Subsequence Bolt 3 990 Sep-22-2023, 08:09 AM
Last Post: Bolt
  [SOLVED] [regex] Why isn't possible substring ignored? Winfried 4 1,124 Apr-08-2023, 06:36 PM
Last Post: Winfried
  ValueError: substring not found nby2001 4 8,034 Aug-08-2022, 11:16 AM
Last Post: rob101
  Match substring using regex Pavel_47 6 1,488 Jul-18-2022, 07:46 AM
Last Post: Pavel_47
  longest palindromic subsequence DP solution bug usercat123 9 2,398 Feb-05-2022, 06:00 AM
Last Post: deanhystad
  Substring Counting shelbyahn 4 6,187 Jan-13-2022, 10:08 AM
Last Post: krisputas
  What is the Python Implementation for This? pythonflea 5 2,533 Feb-08-2021, 08:18 PM
Last Post: buran
  Python Substring muzikman 4 2,359 Dec-01-2020, 03:07 PM
Last Post: deanhystad
  Removing items from list if containing a substring pythonnewbie138 2 2,236 Aug-27-2020, 10:20 PM
Last Post: pythonnewbie138

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020