Skip to content

1100. Find K-Length Substrings With No Repeated Characters 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int numKLenSubstrNoRepeats(string s, int k) {
    int ans = 0;
    int unique = 0;
    vector<int> count(26);

    for (int i = 0; i < s.length(); ++i) {
      if (++count[s[i] - 'a'] == 1)
        ++unique;
      if (i >= k && --count[s[i - k] - 'a'] == 0)
        --unique;
      if (unique == k)
        ++ans;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int numKLenSubstrNoRepeats(String s, int k) {
    int ans = 0;
    int unique = 0;
    int[] count = new int[26];

    for (int i = 0; i < s.length(); ++i) {
      if (++count[s.charAt(i) - 'a'] == 1)
        ++unique;
      if (i >= k && --count[s.charAt(i - k) - 'a'] == 0)
        --unique;
      if (unique == k)
        ++ans;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def numKLenSubstrNoRepeats(self, s: str, k: int) -> int:
    ans = 0
    unique = 0
    count = collections.Counter()

    for i, c in enumerate(s):
      count[c] += 1
      if count[c] == 1:
        unique += 1
      if i >= k:
        count[s[i - k]] -= 1
        if count[s[i - k]] == 0:
          unique -= 1
        if unique == k:
          ans += 1

    return ans