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

Commit69e3c27

Browse files
add one more solution for 821
1 parent284e03f commit69e3c27

File tree

2 files changed

+51
-11
lines changed

2 files changed

+51
-11
lines changed

‎src/main/java/com/fishercoder/solutions/_821.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
packagecom.fishercoder.solutions;
22

3+
importjava.util.Arrays;
34
importjava.util.TreeSet;
45

56
publicclass_821 {
@@ -27,4 +28,35 @@ public int[] shortestToChar(String S, char C) {
2728
returnresult;
2829
}
2930
}
31+
32+
publicstaticclassSolution2 {
33+
publicint[]shortestToChar(Strings,charc) {
34+
int[]result =newint[s.length()];
35+
Arrays.fill(result,Integer.MAX_VALUE);
36+
for (inti =0;i <s.length();i++) {
37+
if (s.charAt(i) ==c) {
38+
result[i] =0;
39+
}
40+
}
41+
for (inti =0;i <s.length();i++) {
42+
if (result[i] !=0) {
43+
intj =i -1;
44+
while (j >=0 &&result[j] !=0) {
45+
j--;
46+
}
47+
if (j >=0) {
48+
result[i] =i -j;
49+
}
50+
j =i +1;
51+
while (j <s.length() &&result[j] !=0) {
52+
j++;
53+
}
54+
if (j <s.length()) {
55+
result[i] =Math.min(result[i],j -i);
56+
}
57+
}
58+
}
59+
returnresult;
60+
}
61+
}
3062
}

‎src/test/java/com/fishercoder/_821Test.java

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,25 @@
77
importstaticorg.junit.Assert.assertArrayEquals;
88

99
publicclass_821Test {
10-
privatestatic_821.Solution1solution1;
11-
privatestaticint[]expected;
10+
privatestatic_821.Solution1solution1;
11+
privatestatic_821.Solution2solution2;
12+
privatestaticint[]expected;
1213

13-
@BeforeClass
14-
publicstaticvoidsetup() {
15-
solution1 =new_821.Solution1();
16-
}
14+
@BeforeClass
15+
publicstaticvoidsetup() {
16+
solution1 =new_821.Solution1();
17+
solution2 =new_821.Solution2();
18+
}
1719

18-
@Test
19-
publicvoidtest1() {
20-
expected =newint[] {3,2,1,0,1,0,0,1,2,2,1,0};
21-
assertArrayEquals(expected,solution1.shortestToChar("loveleetcode",'e'));
22-
}
20+
@Test
21+
publicvoidtest1() {
22+
expected =newint[]{3,2,1,0,1,0,0,1,2,2,1,0};
23+
assertArrayEquals(expected,solution1.shortestToChar("loveleetcode",'e'));
24+
}
25+
26+
@Test
27+
publicvoidtest2() {
28+
expected =newint[]{3,2,1,0,1,0,0,1,2,2,1,0};
29+
assertArrayEquals(expected,solution2.shortestToChar("loveleetcode",'e'));
30+
}
2331
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp