Problem 222
Longest Common Substring
Medium · 20 pts · String, Dynamic Programming
Problem
You are given two strings S and T. Find the length of the longest string that appears as a contiguous substring of both. Unlike a subsequence, a substring cannot skip characters. If the strings share no character at all, the answer is 0. Use dynamic programming: let dp[i][j] be the length of the longest common substring ending exactly at S[i - 1] and T[j - 1]. If those characters are equal, dp[i][j] = dp[i - 1][j - 1] + 1; otherwise it is 0. The answer is the largest value in the table.
Input
Two lines: strings S and T of lowercase letters.
Output
Print the length of the longest common substring.
Constraints
1 <= |S|, |T| <= 1000
Example input
xabcdy zabcdq
Example output
4
Explanation
"xabcdy" and "zabcdq" both contain the block "abcd", of length 4. No longer block appears in both, so the answer is 4.