Given a string s, return the length of the longest repeating substrings. If no repeating substring exists, return 0.
Example 1:
Input: s = "abcd"
Output: 0
Explanation: There is no repeating substring.
Example 2:
Input: s = "abbaba"
Output: 2
Explanation: The longest repeating substrings are "ab" and "ba", each of which occurs twice.
Example 3:
Input: s = "aabcaabdaab"
Output: 3
Explanation: The longest repeating substring is "aab", which occurs 3 times.
Constraints:
1 <= s.length <= 2000
s consists of lowercase English letters.
Solutions
Solution 1: Dynamic Programming
Thinking
A longest repeated substring can use a suffix array or hashed binary search; \(n\le 2000\) also allows an \(O(n^2)\) DP. The common suffix ending at distinct \(i>j\) grows by one when \(s[i]=s[j]\).
\(f[i][j]\) is that length. Enumerate \(i\) and \(j<i\), transfer on equality, and track the global maximum.
The answer is the largest \(f[i][j]\).
We define \(f[i][j]\) to represent the length of the longest repeating substring ending with \(s[i]\) and \(s[j]\). Initially, \(f[i][j]=0\).
We enumerate \(i\) in the range \([1, n)\) and enumerate \(j\) in the range \([0, i)\). If \(s[i]=s[j]\), then we have: