Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit4dd42b4

Browse files
add a solution for 159
1 parenta1fada8 commit4dd42b4

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
returnmaxLength;
3434
}
3535
}
36+
37+
publicstaticclassSolution2 {
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+
publicintlengthOfLongestSubstringTwoDistinct(Strings) {
44+
intdistinct =0;
45+
intans =0;
46+
intleft =0;
47+
intright =0;
48+
int[]counts =newint[256];
49+
while (right <s.length()) {
50+
charc1 =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+
charc2 =s.charAt(left);
61+
counts[c2]--;
62+
if (counts[c2] ==0) {
63+
distinct--;
64+
}
65+
left++;
66+
}
67+
}
68+
returnans;
69+
}
70+
}
3671
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
packagecom.fishercoder;
2+
3+
importcom.fishercoder.solutions._159;
4+
importorg.junit.BeforeClass;
5+
importorg.junit.Test;
6+
7+
importstaticorg.junit.Assert.assertEquals;
8+
9+
publicclass_159Test {
10+
privatestatic_159.Solution1solution1;
11+
privatestatic_159.Solution2solution2;
12+
privatestaticStrings;
13+
privatestaticintexpected;
14+
15+
@BeforeClass
16+
publicstaticvoidsetup() {
17+
solution1 =new_159.Solution1();
18+
solution2 =new_159.Solution2();
19+
}
20+
21+
@Test
22+
publicvoidtest1() {
23+
s ="eceba";
24+
expected =3;
25+
assertEquals(expected,solution1.lengthOfLongestSubstringTwoDistinct(s));
26+
assertEquals(expected,solution2.lengthOfLongestSubstringTwoDistinct(s));
27+
}
28+
29+
30+
@Test
31+
publicvoidtest2() {
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)

[8]ページ先頭

©2009-2025 Movatter.jp