Skip to content

Commit ed95af1

Browse files
committed
Longest distinct substring problem.
1 parent 23004eb commit ed95af1

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

GrokkingSlidingWindow.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.cunningdj.grokJava;
22

33
import java.util.HashMap;
4+
import java.util.HashSet;
45

56
class GrokkingSlidingWindow {
67
public static void main(String[] args) {
@@ -25,6 +26,44 @@ public static void main(String[] args) {
2526
tester.intEquals(5, maxFruitsTwoBaskets(new char[]{A,C,A,A,A,B,B}), testTitle);
2627
// TESTING: middle max
2728
tester.intEquals(5, maxFruitsTwoBaskets(new char[]{A,C,A,A,A,B,B,C,A}), testTitle);
29+
30+
// LONGEST_SUBSTRING_DISTINCT_CHARS
31+
testTitle = "LONGEST_SUBSTRING_DISTINCT_CHARS";
32+
// TESTING: middle
33+
tester.intEquals(4, longestSubstringDistinctCharacters("aaabcdaa"), testTitle);
34+
// TESTING: beginning
35+
tester.intEquals(4, longestSubstringDistinctCharacters("abcdaaa"), testTitle);
36+
// TESTING: end
37+
tester.intEquals(4, longestSubstringDistinctCharacters("aaabcda"), testTitle);
38+
// TESTING: all same
39+
tester.intEquals(1, longestSubstringDistinctCharacters("aaaa"), testTitle);
40+
// TESTING: all unique
41+
tester.intEquals(5, longestSubstringDistinctCharacters("abcde"), testTitle);
42+
// TESTING: only one
43+
tester.intEquals(1, longestSubstringDistinctCharacters("a"), testTitle);
44+
}
45+
46+
public static int longestSubstringDistinctCharacters(String str) {
47+
int n = str.length();
48+
if (n < 1) {
49+
return 0;
50+
}
51+
int start = 0;
52+
int end = 0;
53+
HashSet<Character> prevChars = new HashSet<Character>();
54+
int maxLength = 0;
55+
int currLength = 0;
56+
while (end < n) {
57+
char c = str.charAt(end);
58+
while (start < end && prevChars.contains(c)) {
59+
prevChars.remove(str.charAt(start));
60+
++start;
61+
}
62+
prevChars.add(c);
63+
maxLength = Math.max(maxLength, prevChars.size());
64+
++end;
65+
}
66+
return maxLength;
2867
}
2968

3069
public static int maxFruitsTwoBaskets(char[] fruits) {

0 commit comments

Comments
 (0)