-
Notifications
You must be signed in to change notification settings - Fork 46
/
_821.java
38 lines (31 loc) · 876 Bytes
/
_821.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import java.util.Arrays;
import java.util.TreeSet;
/**
* LeetCode 821 - Shortest Distance to a Character
* <p>
* Brute-force
*/
public class _821 {
public int[] shortestToChar(String S, char C) {
TreeSet<Integer> tree = new TreeSet<>();
int[] res = new int[S.length()];
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == C) {
tree.add(i);
}
}
for (int i = 0; i < S.length(); i++) {
res[i] = Integer.MAX_VALUE;
Integer pos = null;
pos = tree.floor(i);
if (pos != null) {
res[i] = Math.min(res[i], Math.abs(pos - i));
}
pos = tree.ceiling(i);
if (pos != null) {
res[i] = Math.min(res[i], Math.abs(pos - i));
}
}
return res;
}
}