返回介绍

solution / 1000-1099 / 1062.Longest Repeating Substring / README_EN

发布于 2024-06-17 01:03:31 字数 3358 浏览 0 评论 0 收藏 0

1062. Longest Repeating Substring

中文文档

Description

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

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
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文