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


Possibly Related Threads…
Thread Author Replies Views Last Post
  extract substring from a string before a word !! evilcode1 3 2,756 Nov-08-2023, 12:18 AM
Last Post: evilcode1
  Python code for Longest Common Subsequence Bolt 3 3,004 Sep-22-2023, 08:09 AM
Last Post: Bolt
  [SOLVED] [regex] Why isn't possible substring ignored? Winfried 4 2,877 Apr-08-2023, 06:36 PM
Last Post: Winfried
  ValueError: substring not found nby2001 4 12,966 Aug-08-2022, 11:16 AM
Last Post: rob101
  Match substring using regex Pavel_47 6 3,532 Jul-18-2022, 07:46 AM
Last Post: Pavel_47
  longest palindromic subsequence DP solution bug usercat123 9 5,237 Feb-05-2022, 06:00 AM
Last Post: deanhystad
  Substring Counting shelbyahn 4 8,376 Jan-13-2022, 10:08 AM
Last Post: krisputas
  a function common to methods of a class Skaperen 7 5,136 Oct-04-2021, 07:07 PM
Last Post: Skaperen
  Find Common Elements in 2 list quest 4 4,429 Apr-14-2021, 03:57 PM
Last Post: quest
  What is the Python Implementation for This? pythonflea 5 4,335 Feb-08-2021, 08:18 PM
Last Post: buran

Forum Jump:

User Panel Messages

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