LeetCode 821. Shortest Distance to a Character
考点 | 难度 |
---|---|
Array | Easy |
题目
Given a string s
and a character c
that occurs in s
, return an array of integers answer where answer.length == s.length
and answer[i]
is the distance from index i
to the closest occurrence of character c
in s
.
The distance between two indices i
and j
is abs(i - j)
, where abs
is the absolute value function.
思路
从左边和右边分别算最近的C
的距离,选更小的。
prev
设置为Integer.MIN_VALUE / 2
是因为如果prev
等于Integer.MIN_VALUE
,i-prev
会导致overload。
答案
public int[] shortestToChar(String S, char C) {
int N = S.length();
int[] ans = new int[N];
int prev = Integer.MIN_VALUE / 2;
for (int i = 0; i < N; ++i) {
if (S.charAt(i) == C) prev = i;
ans[i] = i - prev;
}
prev = Integer.MAX_VALUE / 2;
for (int i = N-1; i >= 0; --i) {
if (S.charAt(i) == C) prev = i;
ans[i] = Math.min(ans[i], prev - i);
}
return ans;
}