There is a special typewriter with lowercase English letters 'a' to 'z' arranged in a circle with a pointer. A character can only be typed if the pointer is pointing to that character. The pointer is initially pointing to the character 'a'.

Each second, you may perform one of the following operations:
- Move the pointer one character counterclockwise or clockwise.
- Type the character the pointer is currently on.
Given a string word, return the minimum number of seconds to type out the characters in word.
Example 1:
Input: word = "abc"
Output: 5
Explanation:
The characters are printed as follows:
- Type the character 'a' in 1 second since the pointer is initially on 'a'.
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer clockwise to 'c' in 1 second.
- Type the character 'c' in 1 second.
Example 2:
Input: word = "bza"
Output: 7
Explanation:
The characters are printed as follows:
- Move the pointer clockwise to 'b' in 1 second.
- Type the character 'b' in 1 second.
- Move the pointer counterclockwise to 'z' in 2 seconds.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'a' in 1 second.
- Type the character 'a' in 1 second.
Example 3:
Input: word = "zjpc"
Output: 34
Explanation:
The characters are printed as follows:
- Move the pointer counterclockwise to 'z' in 1 second.
- Type the character 'z' in 1 second.
- Move the pointer clockwise to 'j' in 10 seconds.
- Type the character 'j' in 1 second.
- Move the pointer clockwise to 'p' in 6 seconds.
- Type the character 'p' in 1 second.
- Move the pointer counterclockwise to 'c' in 13 seconds.
- Type the character 'c' in 1 second.
출처 : https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter/description/
풀이
function minTimeToType(word: string): number {
const base = 'a'.charCodeAt(0);
const last = 'z'.charCodeAt(0);
let p = base;
let count = 0;
for (let i = 0; i < word.length; i++) {
const c = word.charCodeAt(i);
const max = Math.max(p, c);
const min = Math.min(p, c);
count += Math.min(last - max + min - base + 1, max - min) + 1;
p = c;
}
return count;
}
주어진 단어를 타이핑하는 데 걸리는 최소 시간을 계산하는 함수
count += Math.min(last - max + min - base + 1, max - min) + 1;
- 고리 구조를 이용한 이동 거리: last - max + min - base + 1
- last는 'z'의 유니코드 값 (122)
- base는 'a'의 유니코드 값 (97)
- 예를 들어, 'b'에서 'z'로 이동하는 경우:
- max는 'z'의 유니코드 값인 122
- min은 'b'의 유니코드 값인 98
- 계산식: 122 - 122 + 98 - 97 + 1 = 2
- 직선 구조를 이용한 이동 거리: max - min
- 예를 들어, 'b'에서 'z'로 이동하는 경우:
- max는 'z'의 유니코드 값인 122
- min은 'b'의 유니코드 값인 98
- 계산식: 122 - 98 = 24
- 예를 들어, 'b'에서 'z'로 이동하는 경우:
- 두 값 중 작은 값을 선택하여 이동 거리를 계산
'LeetCode' 카테고리의 다른 글
| 938. Range Sum of BST / TypeScript (0) | 2024.05.28 |
|---|---|
| 3038. Maximum Number of Operations With the Same Score I / TypeScript (0) | 2024.05.27 |
| 563. Binary Tree Tilt (0) | 2024.05.24 |
| 1640. Check Array Formation Through Concatenation / TypeScript (0) | 2024.05.21 |
| 228. Summary Ranges / TypeScript (0) | 2024.05.20 |