[LeetCode] 1974. Minimum Time to Type Word Using Special Typewriter

Chobby·2일 전
1

LeetCode

목록 보기
642/650

😎풀이

  1. 원형 크기 정의 (a ~ z)
  2. 모든 문자 코드로 변환
  3. 문자코드 순회
    3-1. 문자 선택 시 반드시 1초가 소요되므로 미리 증가
    3-2. 시계 방향으로 탐색했을 때 소요 시간 확인
    3-3. 반시계 방향으로 탐색했을 때 소요 시간 확인
    3-4. 시계/반시계 중 효율적인 탐색 소요 시간 저긻
    3-5. 포인터 현재 위치로 변경
  4. 최종 소요 시간 반환
function minTimeToType(word: string): number {
    const n = 26
    const wordToCode = [...word].map(a => a.charCodeAt(0) - 96)
    let spendTime = 0
    let curPointer = 1
    for(const code of wordToCode) {
        spendTime++
        const clockwise = (code - curPointer + n) % n 
        const counterClockwise = (curPointer - code + n) % n
        spendTime += Math.min(clockwise, counterClockwise)
        curPointer = code
    }
    return spendTime
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글