Skip to content

Commit 4dd42b4

Browse files
add a solution for 159
1 parent a1fada8 commit 4dd42b4

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

src/main/java/com/fishercoder/solutions/_159.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,39 @@ public int lengthOfLongestSubstringTwoDistinct(String s) {
3333
return maxLength;
3434
}
3535
}
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+
}
3671
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
}

0 commit comments

Comments
 (0)