@@ -48,7 +48,7 @@ public static int lengthOfLongestSubstringKDistinct(String str, int k) {
48
48
49
49
// when number of distinct characters in the window exceeds k:
50
50
// - update length
51
- // - remove the first character in the window or reduce its count if the window had more than one of this character
51
+ // - remove the first character in the window or reduce its count if the window has more than one of this character
52
52
// - lastly, move the window forward
53
53
if (letterCountInWindow .keySet ().size () > k ) {
54
54
char firstChar = str .charAt (left );
@@ -64,17 +64,18 @@ public static int lengthOfLongestSubstringKDistinct(String str, int k) {
64
64
right ++;
65
65
}
66
66
67
- return length == 0 ? right - left : length ;
67
+ return Math . max ( length , right - left ) ;
68
68
}
69
69
70
70
public static void main (String [] args ) {
71
71
assertEquals (3 , lengthOfLongestSubstringKDistinct ("eceba" , 2 ));
72
72
assertEquals (7 , lengthOfLongestSubstringKDistinct ("eceeeeeba" , 2 ));
73
+ assertEquals (12 , lengthOfLongestSubstringKDistinct ("bbbeeeeebaaaaaaaaaaa" , 2 ));
73
74
assertEquals (2 , lengthOfLongestSubstringKDistinct ("abcdef" , 2 ));
74
75
assertEquals (1 , lengthOfLongestSubstringKDistinct ("a" , 1 ));
76
+ assertEquals (0 , lengthOfLongestSubstringKDistinct ("aa" , 0 ));
75
77
assertEquals (2 , lengthOfLongestSubstringKDistinct ("aa" , 1 ));
76
78
assertEquals (3 , lengthOfLongestSubstringKDistinct ("aaa" , 1 ));
77
- assertEquals (0 , lengthOfLongestSubstringKDistinct ("aa" , 0 ));
78
79
assertEquals (3 , lengthOfLongestSubstringKDistinct ("aab" , 2 ));
79
80
assertEquals (8 , lengthOfLongestSubstringKDistinct ("abcabcbb" , 3 ));
80
81
assertEquals (5 , lengthOfLongestSubstringKDistinct ("pwwkew" , 3 ));
0 commit comments