https://leetcode.com/problems/shortest-distance-to-a-character/description/
Solution 1.
/**
* @param {string} s
* @param {character} c
* @return {number[]}
*/
var shortestToChar = function (s, c) {
const targets = [];
for (let i = 0; i < s.length; i++) {
if (s[i] === c) {
targets.push(i);
}
}
let targetIndex = 0;
const result = [];
for (let j = 0; j < s.length; j++) {
const nextIndex = targetIndex + 1;
if (!isNaN(targets[nextIndex])) {
result.push(
Math.min(
Math.abs(j - targets[targetIndex]),
Math.abs(j - targets[nextIndex]),
),
);
if (j - targets[nextIndex] === 0) {
targetIndex++;
}
} else {
if (s[j] === c) {
result.push(0);
} else {
result.push(Math.abs(j - targets[targetIndex]));
}
}
}
return result;
};
Runtime 131 ms Beats 21.28%
Memory 44.5 MB Beats 54.4%