LeetCode 1100. Find K-Length Substrings With No Repeated Characters Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
1100. Find K-Length Substrings With No Repeated Characters

Description

Given a string s and an integer k, return the number of substrings in s of length k with no repeated characters.

 

Example 1:

Input: s = "havefunonleetcode", k = 5
Output: 6
Explanation: There are 6 substrings they are: 'havef','avefu','vefun','efuno','etcod','tcode'.

Example 2:

Input: s = "home", k = 5
Output: 0
Explanation: Notice k can be larger than the length of s. In this case, it is not possible to find any substring.

 

Constraints:

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

Solutions

Solution 1: Sliding Window + Hash Table

We maintain a sliding window of length k, and use a hash table cnt to count the occurrences of each character in the window.

First, we add the first k characters of the string s to the hash table cnt, and check whether the size of cnt is equal to k. If it is, it means that all characters in the window are different, and the answer ans is incremented by one.

Next, we start to traverse the string s from k. Each time we add s[i] to the hash table cnt, and at the same time subtract s[i-k] from the hash table cnt by one. If cnt[s[i-k]] is equal to 0 after subtraction, we remove s[i-k] from the hash table cnt. If the size of the hash table cnt is equal to k at this time, it means that all characters in the window are different, and the answer ans is incremented by one.

Finally, return the answer ans.

The time complexity is O(n), and the space complexity is O(min(k, |Σ|)), where n is the length of the string s; and Σ is the character set, in this problem the character set is lowercase English letters, so |Σ| = 26.

PythonJavaC++GoTypeScriptPHP
class Solution: def numKLenSubstrNoRepeats(self, s: str, k: int) -> int: cnt = Counter(s[:k]) ans = int(len(cnt) == k) for i in range(k, len(s)): cnt[s[i]] += 1 cnt[s[i - k]] -= 1 if cnt[s[i - k]] == 0: cnt.pop(s[i - k]) ans += int(len(cnt) == k) 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 !