Find K-Length Substrings With No Repeated Characters

Given a string S, return the number of substrings 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 is not possible to find any substring.

 

Note:

  1. 1 <= S.length <= 10^4
  2. All characters of S are lowercase English letters.
  3. 1 <= K <= 10^4

Solution:

class Solution {
    public int numKLenSubstrNoRepeats(String S, int K) {
        int[] count = new int[26];
        int left = 0, right = 0, result = 0;
        while (right < S.length()) {
            char c = S.charAt(right);
            count[c - 'a'] ++;
            while (left <= right && (count[c - 'a'] > 1 || right - left + 1 > K)) {
                char l = S.charAt(left ++);     
                count[l - 'a'] --;
            }
            if (right - left + 1 == K) {
                result ++;
            }
            right ++;
        }
        return result;
    }
}