LeetCode 1044. Longest Duplicate Substring Solution in Java, C++, Python & Go | Explanation + Code

CoderIndeed
0
1044. Longest Duplicate Substring

Description

Given a string s, consider all duplicated substrings: (contiguous) substrings of s that occur 2 or more times. The occurrences may overlap.

Return any duplicated substring that has the longest possible length. If s does not have a duplicated substring, the answer is "".

 

Example 1:

Input: s = "banana"
Output: "ana"

Example 2:

Input: s = "abcd"
Output: ""

 

Constraints:

  • 2 <= s.length <= 3 * 104
  • s consists of lowercase English letters.

Solutions

Solution 1

PythonJavaC++Go
class Solution: def longestDupSubstring(self, s: str) -> str: def check(l): vis = set() for i in range(n - l + 1): t = s[i : i + l] if t in vis: return t vis.add(t) return '' n = len(s) left, right = 0, n ans = '' while left < right: mid = (left + right + 1) >> 1 t = check(mid) ans = t or ans if t: left = mid else: right = mid - 1 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 !