[LeetCode] 821. Shortest Distance to a Character

Chobby·6일 전
1

LeetCode

목록 보기
410/427

😎풀이

  1. s내에서 처음 c가 나오는 위치와 그 다음 c가 나오는 위치를 찾는다.
    1-1. 이 때, 만약 c가 한 번 밖에 나오지 않는다면, nextCIdxInfinity로 설정하여 항상 첫 c 위치와 거리를 비교할 수 있도록 한다.
  2. s를 순회하며, 이전 c 위치와 다음 c 위치 중 가까운 위치를 비교, 만약 현재 값이 c라면, 이전 c 인덱스를 현재로 갱신하고 다음 c 위치를 탐색하며 반복한다.
  3. 각 위치에서의 가장 가까운 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
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글