LeetCode 1062. Longest Repeating Substring Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
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: Dynamic Programming

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:

f[i][j]= \begin{cases} f[i-1][j-1]+1, & j>0 \ 1, & j=0 \end{cases}

The answer is the maximum value of all f[i][j].

The time complexity is O(n2), and the space complexity is O(n2). Where n is the length of the string s.

Similar problems:

PythonJavaC++GoTypeScriptRust
class Solution: def longestRepeatingSubstring(self, s: str) -> int: n = len(s) f = [[0] * n for _ in range(n)] ans = 0 for i in range(1, n): for j in range(i): if s[i] == s[j]: f[i][j] = 1 + (f[i - 1][j - 1] if j else 0) ans = max(ans, f[i][j]) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !