题目描述
思路
遍历
最简单的思路就是对于每个位置正着遍历一遍,再反着遍历一遍,分别记录两次遍历它离前面遍历到的最近的字符c的距离,取最小值存到ans数组中即可。
Python实现
class Solution:
def shortestToChar(self, s: str, c: str) -> List[int]:
n = len(s)
ans, idx = [0] * n, -n
for i, ch in enumerate(s):
if ch == c:
idx = i
ans[i] = i - idx
idx = 2*n
for i in range(n-1, -1, -1):
if s[i] == c:
idx = i
ans[i] = min(ans[i], idx-i)
return ans
Java实现
class Solution {
public int[] shortestToChar(String s, char c) {
int n = s.length();
int[] ans = new int[n];
int idx = -n;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == c) {
idx = i;
}
ans[i] = i - idx;
}
idx = 2*n;
for (int i = n-1; i >= 0; i--) {
if (s.charAt(i) == c) {
idx = i;
}
ans[i] = Math.min(ans[i], idx-i);
}
return ans;
}
}