Skip to content

Commit 69e3c27

Browse files
add one more solution for 821
1 parent 284e03f commit 69e3c27

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
package com.fishercoder.solutions;
22

3+
import java.util.Arrays;
34
import java.util.TreeSet;
45

56
public class _821 {
@@ -27,4 +28,35 @@ public int[] shortestToChar(String S, char C) {
2728
return result;
2829
}
2930
}
31+
32+
public static class Solution2 {
33+
public int[] shortestToChar(String s, char c) {
34+
int[] result = new int[s.length()];
35+
Arrays.fill(result, Integer.MAX_VALUE);
36+
for (int i = 0; i < s.length(); i++) {
37+
if (s.charAt(i) == c) {
38+
result[i] = 0;
39+
}
40+
}
41+
for (int i = 0; i < s.length(); i++) {
42+
if (result[i] != 0) {
43+
int j = 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+
return result;
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
import static org.junit.Assert.assertArrayEquals;
88

99
public class _821Test {
10-
private static _821.Solution1 solution1;
11-
private static int[] expected;
10+
private static _821.Solution1 solution1;
11+
private static _821.Solution2 solution2;
12+
private static int[] expected;
1213

13-
@BeforeClass
14-
public static void setup() {
15-
solution1 = new _821.Solution1();
16-
}
14+
@BeforeClass
15+
public static void setup() {
16+
solution1 = new _821.Solution1();
17+
solution2 = new _821.Solution2();
18+
}
1719

18-
@Test
19-
public void test1() {
20-
expected = new int[] {3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0};
21-
assertArrayEquals(expected, solution1.shortestToChar("loveleetcode", 'e'));
22-
}
20+
@Test
21+
public void test1() {
22+
expected = new int[]{3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0};
23+
assertArrayEquals(expected, solution1.shortestToChar("loveleetcode", 'e'));
24+
}
25+
26+
@Test
27+
public void test2() {
28+
expected = new int[]{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)