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] := # of repeating chars 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] := # of repeating chars 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;
  }
}