1

I've been trying to learn Dynamic Programming. And I have come across two seemingly similar problems "Longest Common Subsequence" and "Longest Common Substring"

So we assume we have 2 strings str1 and str2.

  • For Longest Common Subsequence, we create the dp table as such:
if str1[i] != str2[j]:
    dp[i][j] = max(dp[i-1][j], sp[i][j-1])
else:
    dp[i][j] = 1 + dp[i-1][j-1]

Following the same intuition, for "Longest Common Substring" can we do the following:

if str1[i] != str2[j]:
    dp[i][j] = max(dp[i-1][j], sp[i][j-1])
else:
    if str1[i-1] == str2[j-1]:
        dp[i][j] = 1 + dp[i-1][j-1]
    else:
        dp[i][j] = 1 + dp[i-1][j-1]

The check if str1[i-1] == str2[j-1] confirms that we are checking for substrings and not subsequence

Bernerd
  • 68
  • 5
  • Just to confirm: the difference between Longest Common Subsequence and Longest Common Substring is that in Longest Common Substring the elements in the common subsequence must be consecutive. – Jarvis Dec 12 '22 at 09:10

1 Answers1

0

I didn't understand what you are asking, but I'll try to give a good explanation for the Longest Common Substring.

Let DP[x][y] be the maximum common substring, considering str1[0..x] and str2[0..y].

Consider that we are computing DP[a][b], we always have the possibility of not using this character = max( DP[a][b - 1], DP[a - 1][b] ) and if str1[a] == str2[b] we can also take the answer of DP[a - 1][b - 1] + 1 ( this +1 exist because we have found a new matching character )

// This does not depend on s[i] == s[j]
dp[i][j] = max( dp[i][j - 1], dp[i - 1][j] )

if str1[i] == str2[j]:
    dp[i][j] = max( dp[i][j], dp[i - 1][j - 1] + 1 )