
😎풀이
s
내에서 처음 c
가 나오는 위치와 그 다음 c
가 나오는 위치를 찾는다.
1-1. 이 때, 만약 c
가 한 번 밖에 나오지 않는다면, nextCIdx
를 Infinity
로 설정하여 항상 첫 c
위치와 거리를 비교할 수 있도록 한다.
s
를 순회하며, 이전 c
위치와 다음 c
위치 중 가까운 위치를 비교, 만약 현재 값이 c
라면, 이전 c
인덱스를 현재로 갱신하고 다음 c
위치를 탐색하며 반복한다.
- 각 위치에서의 가장 가까운
c
의 거리를 반환한다.
function shortestToChar(s: string, c: string): number[] {
const distances = []
let prevCIdx = s.indexOf(c)
let nextCIdx = s.indexOf(c, prevCIdx + 1)
if(nextCIdx === -1) nextCIdx = Infinity
for(let i = 0; i < s.length; i++) {
const prevDist = Math.abs(prevCIdx - i)
const nextDist = Math.abs(nextCIdx - i)
distances.push(Math.min(prevDist, nextDist))
if(s[i] === c) {
prevCIdx = i
nextCIdx = s.indexOf(c, i + 1)
}
}
return distances
};