Leetcode 821. Shortest Distance to a Character
Given a string s
and a character c
that occurs in s
, return an array of integers representing the shortest distance from the character c
in the string s
.
s
be uppercase or lowercase?
s
can have any characters including uppercase and lowercase letters.c
be an uppercase or lowercase letter?
c
can be any character including uppercase and lowercase letters.s
)?
s
is very short, where c
is the first or the last character, or where c
appears consecutively in s
.Integer.MAX_VALUE
) initially.c
and update the shortest distance using this position.c
and update the shortest distances from this run through.c
.public class Solution {
public int[] shortestToChar(String s, char c) {
int n = s.length();
int[] result = new int[n];
// Initialize all distances to a large number
int inf = Integer.MAX_VALUE;
// Left to right pass
int position = -inf;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == c) {
position = i;
}
result[i] = i - position;
}
// Right to left pass
position = inf;
for (int i = n - 1; i >= 0; i--) {
if (s.charAt(i) == c) {
position = i;
}
result[i] = Math.min(result[i], position - i);
}
return result;
}
}
This approach ensures an efficient solution to the problem while maintaining clarity and simplicity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?