Given a string S
and a character C
, return an array of integers representing the shortest distance from the character C
in the string.
Example 1:
Input: S = "loveleetcode", C = 'e' Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
思路:扫两遍, O(N),第一遍从左往右,用i - pos来算到左边的C的最短距离
扫描完后,从右往左扫,算到右边C的最短距离,两个取最小值就是答案;
注意pos initial = -n;
class Solution {
public int[] shortestToChar(String S, char C) {
if(S == null || S.length() == 0) {
return new int[0];
}
int n = S.length();
int[] res = new int[n];
int pos = -n;
for(int i = 0; i < n; i++) {
char sc = S.charAt(i);
if(sc == C) {
pos = i;
}
res[i] = i - pos;
}
// 循环完后,pos代表最后一个C的位置;
for(int i = n - 1; i >= 0; i--) {
char sc = S.charAt(i);
if(sc == C) {
pos = i;
}
res[i] = Math.min(res[i], Math.abs(i - pos));
}
return res;
}
}