LeetCode 1316. Distinct Echo Substrings Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1316. Distinct Echo Substrings

Description

Return the number of distinct non-empty substrings of text that can be written as the concatenation of some string with itself (i.e. it can be written as a + a where a is some string).

 

Example 1:

Input: text = "abcabcabc"
Output: 3
Explanation: The 3 substrings are "abcabc", "bcabca" and "cabcab".

Example 2:

Input: text = "leetcodeleetcode"
Output: 2
Explanation: The 2 substrings are "ee" and "leetcodeleetcode".

 

Constraints:

  • 1 <= text.length <= 2000
  • text has only lowercase English letters.

Solutions

Solution 1

PythonJavaC++GoRust
class Solution: def distinctEchoSubstrings(self, text: str) -> int: def get(l, r): return (h[r] - h[l - 1] * p[r - l + 1]) % mod n = len(text) base = 131 mod = int(1e9) + 7 h = [0] * (n + 10) p = [1] * (n + 10) for i, c in enumerate(text): t = ord(c) - ord('a') + 1 h[i + 1] = (h[i] * base) % mod + t p[i + 1] = (p[i] * base) % mod vis = set() for i in range(n - 1): for j in range(i + 1, n, 2): k = (i + j) >> 1 a = get(i + 1, k + 1) b = get(k + 2, j + 1) if a == b: vis.add(a) return len(vis)(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 !