forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1100.java
48 lines (46 loc) · 1.36 KB
/
_1100.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.fishercoder.solutions;
import java.util.HashSet;
import java.util.Set;
/**
* 1100. 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 <= S.length <= 10^4
* All characters of S are lowercase English letters.
* 1 <= K <= 10^4
* */
public class _1100 {
public static class Solution1 {
public int numKLenSubstrNoRepeats(String S, int K) {
int count = 0;
Set<Character> set = new HashSet<>();
for (int i = 0; i <= S.length() - K; i++) {
String string = S.substring(i, i + K);
boolean invalid = false;
for (char c : string.toCharArray()) {
if (!set.add(c)) {
invalid = true;
break;
}
}
count += invalid ? 0 : 1;
set.clear();
}
return count;
}
}
}