Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.
Input: S = "loveleetcode", C = 'e'
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
class Solution {
public int[] shortestToChar(String S, char C) {
int prev = -10000;
Deque<Integer> stack = new ArrayDeque<>();
int[] ret = new int[S.length()];
for (int i = 0; i < S.length(); ++i) {
if (S.charAt(i) == C) {
while (! stack.isEmpty()) {
int peek = stack.pollLast();
ret[peek] = Math.min(peek - prev, i - peek);
}
prev = i;
} else {
stack.offerLast(i);
}
}
while (! stack.isEmpty()) {
int peek = stack.pollLast();
ret[peek] = peek - prev;
}
return ret;
}
}