Skip to content

1062. Longest Repeating Substring 👍

  • Time: $O(n^2)$
  • Space: $O(n^2)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  int longestRepeatingSubstring(string s) {
    const int n = s.length();
    int ans = 0;
    // dp[i][j] := the number of repeating characters of s[0..i) and s[0..j)
    vector<vector<int>> dp(n + 1, vector<int>(n + 1));

    for (int i = 1; i <= n; ++i)
      for (int j = i + 1; j <= n; ++j)
        if (s[i - 1] == s[j - 1]) {
          dp[i][j] = 1 + dp[i - 1][j - 1];
          ans = max(ans, dp[i][j]);
        }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public int longestRepeatingSubstring(String s) {
    final int n = s.length();
    int ans = 0;
    // dp[i][j] := the number of repeating characters of s[0..i) and s[0..j)
    int[][] dp = new int[n + 1][n + 1];

    for (int i = 1; i <= n; ++i)
      for (int j = i + 1; j <= n; ++j)
        if (S.charAt(i - 1) == s.charAt(j - 1)) {
          dp[i][j] = 1 + dp[i - 1][j - 1];
          ans = Math.max(ans, dp[i][j]);
        }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def longestRepeatingSubstring(self, s: str) -> int:
    n = len(s)
    ans = 0
    # dp[i][j] := the number of repeating characters of s[0..i) and s[0..j)
    dp = [[0] * (n + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
      for j in range(i + 1, n + 1):
        if s[i - 1] == s[j - 1]:
          dp[i][j] = 1 + dp[i - 1][j - 1]
          ans = max(ans, dp[i][j])

    return ans