Skip to content

Commit 58d0918

Browse files
refactor 821
1 parent 7daf319 commit 58d0918

File tree

1 file changed

+21
-39
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+21
-39
lines changed

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

+21-39
Original file line numberDiff line numberDiff line change
@@ -2,47 +2,29 @@
22

33
import java.util.TreeSet;
44

5-
/**
6-
* 821. Shortest Distance to a Character
7-
8-
Given a string S and a character C,
9-
return an array of integers representing the shortest distance from the character C in the string.
10-
11-
Example 1:
12-
13-
Input: S = "loveleetcode", C = 'e'
14-
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
15-
16-
Note:
17-
18-
S string length is in [1, 10000].
19-
C is a single character, and guaranteed to be in string S.
20-
All letters in S and C are lowercase.
21-
22-
*/
235
public class _821 {
246

25-
public static class Solution1 {
26-
public int[] shortestToChar(String S, char C) {
27-
int[] result = new int[S.length()];
28-
TreeSet<Integer> cIndices = new TreeSet();
29-
for (int i = 0; i < S.length(); i++) {
30-
if (S.charAt(i) == C) {
31-
cIndices.add(i);
32-
}
33-
}
34-
for (int i = 0; i < S.length(); i++) {
35-
int leftDist = Integer.MAX_VALUE;
36-
if (cIndices.floor(i) != null) {
37-
leftDist = Math.abs(cIndices.floor(i) - i);
38-
}
39-
int rightDist = Integer.MAX_VALUE;
40-
if (cIndices.ceiling(i) != null) {
41-
rightDist = Math.abs(cIndices.ceiling(i) - i);
7+
public static class Solution1 {
8+
public int[] shortestToChar(String S, char C) {
9+
int[] result = new int[S.length()];
10+
TreeSet<Integer> cIndices = new TreeSet();
11+
for (int i = 0; i < S.length(); i++) {
12+
if (S.charAt(i) == C) {
13+
cIndices.add(i);
14+
}
15+
}
16+
for (int i = 0; i < S.length(); i++) {
17+
int leftDist = Integer.MAX_VALUE;
18+
if (cIndices.floor(i) != null) {
19+
leftDist = Math.abs(cIndices.floor(i) - i);
20+
}
21+
int rightDist = Integer.MAX_VALUE;
22+
if (cIndices.ceiling(i) != null) {
23+
rightDist = Math.abs(cIndices.ceiling(i) - i);
24+
}
25+
result[i] = Math.min(leftDist, rightDist);
26+
}
27+
return result;
4228
}
43-
result[i] = Math.min(leftDist, rightDist);
44-
}
45-
return result;
4629
}
47-
}
4830
}

0 commit comments

Comments
 (0)