Given a string s and a character c that occurs in s, return an array of integers answer whereanswer.length == s.lengthandanswer[i]is the shortest distance froms[i]to the charactercins.
Example 1:
Input: s = "loveleetcode", c = "e"
Output: [3,2,1,0,1,0,0,1,2,2,1,0]
public int[] shortestToChar(String s, char c) {
if (s == null || s.isEmpty()) {
return null;
}
int n = s.length();
int[] res = new int[n];
Arrays.fill(res, Integer.MAX_VALUE);
List<Integer> loc = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (s.charAt(i) == c) {
loc.add(i);
}
}
for (int i = 0; i < loc.size(); i++) {
int curLoc = loc.get(i);
for (int j = 0; j < n; j++) {
res[j] = Math.min(Math.abs(curLoc - j), res[j]);
}
}
return res;
}
// solution
public int[] shortestToChar(String s, char c) {
if (s == null || s.isEmpty()) {
return null;
}
int n = s.length();
int[] res = new int[n];
int prev = Integer.MIN_VALUE / 2;
// left to right
for (int i = 0; i < n; i++) {
if (s.charAt(i) == c) {
prev = i;
}
// we are minusing MIN, so will get a really big num here
res[i] = i - prev;
}
prev = Integer.MAX_VALUE / 2;
// right to left
for (int i = n - 1; i >= 0; i--) {
if (s.charAt(i) == c) {
prev = i;
}
// we are using MAX to minus, so will get a really big num here
// them compare with the left_to_right result, take min
res[i] = Math.min(res[i], prev - i);
}
return res;
}