LeetCode 821: Shortest Distance to a Character
Problem Description
Explanation
To solve this problem, we can iterate through the string s
twice. In the first iteration, we find the distance to the closest occurrence of character c
by going from left to right. In the second iteration, we find the distance from the closest occurrence of character c
by going from right to left. We then take the minimum of these two distances at each index to get the final answer array.
-
Algorithm:
- Initialize two arrays
left
andright
of sizes.length()
to store the distances from left and right respectively. - Initialize variables
prev
andresult
to store the previous occurrence index of characterc
and the final answer array. - Iterate through the string
s
from left to right, updatingleft
andprev
. - Iterate through the string
s
from right to left, updatingright
and calculating the minimum distance.
- Initialize two arrays
-
Time Complexity: O(N) where N is the length of the input string
s
. -
Space Complexity: O(N) for the two arrays
left
andright
.
Solutions
class Solution {
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;
}
}
Related LeetCode Problems
Loading editor...