-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathUniqueCharSubstringJava.java
More file actions
49 lines (39 loc) · 1.28 KB
/
UniqueCharSubstringJava.java
File metadata and controls
49 lines (39 loc) · 1.28 KB
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
49
/**
* Given a string and number M find length of the longest substring of M unique chars.
* Input: abbbcddd, M = 3
* Output: 7 (length of bbbcddd)
*/
import java.util.*;
public class UniqueCharSubstringJava {
public static int longest(String str, int m) {
Set<Character> uniqueChars = new HashSet<>();
int currentLen = 0;
int maxLen = 0;
int next = 0;
for (int i = 0, strlen = str.length(); i < strlen; ++i) {
char c = str.charAt(i);
if (uniqueChars.isEmpty()) {
next = i;
while (next < strlen && str.charAt(next) == c) {
++next;
++currentLen;
}
i = next - 1;
}
maxLen = Math.max(currentLen, maxLen);
++currentLen;
uniqueChars.add(c);
if (uniqueChars.size() > m) {
uniqueChars.clear();
currentLen = 0;
i = next;
}
}
return Math.max(maxLen, currentLen);
}
public static void main(String[] args) {
System.out.println( longest("abbbcddd", 3) );
System.out.println( longest("aabbcccddddee", 3) );
System.out.println( longest("aabbcccddddee", 1) );
}
}