2
public int[] shortestToChar(String s, char c) {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 c10
if (index == -1) ans[i] = Integer.MAX_VALUE;11
else ans[i] = i - index;14
// Starting from thr end and storing the distance from the previous c;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 c19
if (index != -1) ans[i] = Math.min(ans[i], index - i);