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