forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_821.java
30 lines (27 loc) · 976 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
package com.fishercoder.solutions;
import java.util.TreeSet;
public class _821 {
public static class Solution1 {
public int[] shortestToChar(String S, char C) {
int[] result = new int[S.length()];
TreeSet<Integer> cIndices = new TreeSet();
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == C) {
cIndices.add(i);
}
}
for (int i = 0; i < S.length(); i++) {
int leftDist = Integer.MAX_VALUE;
if (cIndices.floor(i) != null) {
leftDist = Math.abs(cIndices.floor(i) - i);
}
int rightDist = Integer.MAX_VALUE;
if (cIndices.ceiling(i) != null) {
rightDist = Math.abs(cIndices.ceiling(i) - i);
}
result[i] = Math.min(leftDist, rightDist);
}
return result;
}
}
}