Overview
Unlike Longest Common Subsequence, a Substring must be contiguous. This means the moment two characters don't match, the streak is broken.
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Find the length of the longest contiguous sequence of characters that appear in both strings. A stricter variation of LCS.
Unlike Longest Common Subsequence, a Substring must be contiguous. This means the moment two characters don't match, the streak is broken.
`dp[i][j]` represents the length of the longest common substring ENDING at `s1[i-1]` and `s2[j-1]`.
If characters match, `dp[i][j] = 1 + dp[i-1][j-1]`. If they do NOT match, `dp[i][j] = 0`. We don't carry over the max from Top or Left like in LCS.
Because the longest substring could end anywhere in the strings, the final answer isn't necessarily `dp[m][n]`. We track `maxLen` dynamically during the loop.
| S1 \ S2 | "" | a | b | z | d | f |
|---|---|---|---|---|---|---|
| "" | 0 | 0 | 0 | 0 | 0 | 0 |
| a | 0 | 0 | 0 | 0 | 0 | 0 |
| b | 0 | 0 | 0 | 0 | 0 | 0 |
| c | 0 | 0 | 0 | 0 | 0 | 0 |
| d | 0 | 0 | 0 | 0 | 0 | 0 |
| f | 0 | 0 | 0 | 0 | 0 | 0 |