LeetCode 0395. Longest Substring with At Least K Repeating Characters Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0395. Longest Substring with At Least K Repeating Characters

Description

Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.

if no such substring exists, return 0.

 

Example 1:

Input: s = "aaabb", k = 3
Output: 3
Explanation: The longest substring is "aaa", as 'a' is repeated 3 times.

Example 2:

Input: s = "ababbc", k = 2
Output: 5
Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.

 

Constraints:

  • 1 <= s.length <= 104
  • s consists of only lowercase English letters.
  • 1 <= k <= 105

Solutions

Solution 1

PythonJavaC++Go
class Solution: def longestSubstring(self, s: str, k: int) -> int: def dfs(l, r): cnt = Counter(s[l : r + 1]) split = next((c for c, v in cnt.items() if v < k), '') if not split: return r - l + 1 i = l ans = 0 while i <= r: while i <= r and s[i] == split: i += 1 if i >= r: break j = i while j <= r and s[j] != split: j += 1 t = dfs(i, j - 1) ans = max(ans, t) i = j return ans return dfs(0, len(s) - 1)(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 !