1
class Solution {
2
public int[] shortestToChar(String s, char c) {
3
int n = s.length();
4
int index = -1;
5
int[] ans = new int[n];
6
// Starting from index 0 and storing the distance from the next c;
7
for (int i = 0; i < n; i++) {
8
if (s.charAt(i) == c) index = i; // to store the index of the nearest previous c
9

10
if (index == -1) ans[i] = Integer.MAX_VALUE;
11
else ans[i] = i - index;
12
}
13

14
// Starting from thr end and storing the distance from the previous c;
15
index = -1;
16
for (int i = n - 1; i >= 0; i--) {
17
if (s.charAt(i) == c) index = i; // to store the index of the nearest next c
18

19
if (index != -1) ans[i] = Math.min(ans[i], index - i);
20
}
21
return ans;
22
}
23
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0