This problem asks to find the length of the longest repeating substring within a given string. We can efficiently solve this using dynamic programming.
The core idea is to build a 2D table dp
where dp[i][j]
represents the length of the longest repeating substring ending at indices i
and j
(with i < j
). If s[i] == s[j]
, it means we've potentially extended a repeating substring. The length of this extended substring is 1 plus the length of the substring ending at i-1
and j-1
(dp[i-1][j-1] + 1
). If i
is 0, it means this is the first occurrence of this character, so the length is simply 1. Otherwise, if s[i] != s[j]
, there's no extension, and dp[i][j]
remains 0.
The algorithm iterates through all possible pairs of indices (i, j)
with i < j
, updating dp[i][j]
accordingly and tracking the maximum length encountered so far.
Time Complexity: O(n^2), where n is the length of the string. This is because we iterate through all pairs of indices (i, j)
, resulting in a nested loop with O(n^2) iterations.
Space Complexity: O(n^2) to store the dp
table.
The code implementations below follow the dynamic programming approach explained above.
class Solution:
def longestRepeatingSubstring(self, s: str) -> int:
n = len(s)
dp = [[0] * n for _ in range(n)]
ans = 0
for i in range(n):
for j in range(i + 1, n):
if s[i] == s[j]:
dp[i][j] = dp[i - 1][j - 1] + 1 if i else 1
ans = max(ans, dp[i][j])
return ans
class Solution {
public int longestRepeatingSubstring(String s) {
int n = s.length();
int ans = 0;
int[][] dp = new int[n][n];
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (s.charAt(i) == s.charAt(j)) {
dp[i][j] = i > 0 ? dp[i - 1][j - 1] + 1 : 1;
ans = Math.max(ans, dp[i][j]);
}
}
}
return ans;
}
}
class Solution {
public:
int longestRepeatingSubstring(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n));
int ans = 0;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (s[i] == s[j]) {
dp[i][j] = i ? dp[i - 1][j - 1] + 1 : 1;
ans = max(ans, dp[i][j]);
}
}
}
return ans;
}
};
func longestRepeatingSubstring(s string) int {
n := len(s)
dp := make([][]int, n)
for i := range dp {
dp[i] = make([]int, n)
}
ans := 0
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
if s[i] == s[j] {
if i == 0 {
dp[i][j] = 1
} else {
dp[i][j] = dp[i-1][j-1] + 1
}
ans = max(ans, dp[i][j])
}
}
}
return ans
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
All these code snippets implement the same dynamic programming solution, differing only in syntax and language-specific features. They all achieve a time complexity of O(n^2) and a space complexity of O(n^2).