File tree Expand file tree Collapse file tree 2 files changed +73
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change @@ -33,4 +33,39 @@ public int lengthOfLongestSubstringTwoDistinct(String s) {
33
33
return maxLength ;
34
34
}
35
35
}
36
+
37
+ public static class Solution2 {
38
+ /**
39
+ * My completely original solution, classic sliding window problem:
40
+ * use two pointers, one keeps moving towards the right to expand;
41
+ * the other moves only when we are no longer meeting the requirement, i.e. shrinks.
42
+ */
43
+ public int lengthOfLongestSubstringTwoDistinct (String s ) {
44
+ int distinct = 0 ;
45
+ int ans = 0 ;
46
+ int left = 0 ;
47
+ int right = 0 ;
48
+ int [] counts = new int [256 ];
49
+ while (right < s .length ()) {
50
+ char c1 = s .charAt (right );
51
+ if (counts [c1 ] == 0 ) {
52
+ distinct ++;
53
+ }
54
+ counts [c1 ]++;
55
+ right ++;
56
+ if (distinct <= 2 ) {
57
+ ans = Math .max (ans , right - left );
58
+ }
59
+ while (distinct > 2 ) {
60
+ char c2 = s .charAt (left );
61
+ counts [c2 ]--;
62
+ if (counts [c2 ] == 0 ) {
63
+ distinct --;
64
+ }
65
+ left ++;
66
+ }
67
+ }
68
+ return ans ;
69
+ }
70
+ }
36
71
}
Original file line number Diff line number Diff line change
1
+ package com .fishercoder ;
2
+
3
+ import com .fishercoder .solutions ._159 ;
4
+ import org .junit .BeforeClass ;
5
+ import org .junit .Test ;
6
+
7
+ import static org .junit .Assert .assertEquals ;
8
+
9
+ public class _159Test {
10
+ private static _159 .Solution1 solution1 ;
11
+ private static _159 .Solution2 solution2 ;
12
+ private static String s ;
13
+ private static int expected ;
14
+
15
+ @ BeforeClass
16
+ public static void setup () {
17
+ solution1 = new _159 .Solution1 ();
18
+ solution2 = new _159 .Solution2 ();
19
+ }
20
+
21
+ @ Test
22
+ public void test1 () {
23
+ s = "eceba" ;
24
+ expected = 3 ;
25
+ assertEquals (expected , solution1 .lengthOfLongestSubstringTwoDistinct (s ));
26
+ assertEquals (expected , solution2 .lengthOfLongestSubstringTwoDistinct (s ));
27
+ }
28
+
29
+
30
+ @ Test
31
+ public void test2 () {
32
+ s = "ccaabbb" ;
33
+ expected = 5 ;
34
+ assertEquals (expected , solution1 .lengthOfLongestSubstringTwoDistinct (s ));
35
+ assertEquals (expected , solution2 .lengthOfLongestSubstringTwoDistinct (s ));
36
+ }
37
+
38
+ }
You can’t perform that action at this time.
0 commit comments