class Solution:
def minTimeToType(self, word: str) -> int:
time = 0
curr = 'a'
for ch in word:
diff = abs(ord(ch) - ord(curr))
time += min(diff, 26 - diff) + 1
curr = ch
return time
class Solution {
public:
int minTimeToType(string word) {
int time = 0;
char curr = 'a';
for (char ch : word) {
int diff = abs(ch - curr);
time += min(diff, 26 - diff) + 1;
curr = ch;
}
return time;
}
};
class Solution {
public int minTimeToType(String word) {
int time = 0;
char curr = 'a';
for (char ch : word.toCharArray()) {
int diff = Math.abs(ch - curr);
time += Math.min(diff, 26 - diff) + 1;
curr = ch;
}
return time;
}
}
var minTimeToType = function(word) {
let time = 0;
let curr = 'a';
for (let i = 0; i < word.length; i++) {
let ch = word[i];
let diff = Math.abs(ch.charCodeAt(0) - curr.charCodeAt(0));
time += Math.min(diff, 26 - diff) + 1;
curr = ch;
}
return time;
};
word
consisting only of lowercase English letters. You have a special typewriter with only one character visible at a time, arranged in a circular fashion like a ring. The typewriter starts at the letter 'a'
.
word
, starting from 'a'
.
word.length
≤ 100word
contains only lowercase English lettersword
, we need to decide whether to move clockwise or counterclockwise from the current position. The key insight is that the minimum number of moves is the smaller of:
'a'
(the initial pointer position).word
:
26 - clockwise distance
.ord()
in Python) makes it easy to compute distances.
word = "bza"
:
|ord('b') - ord('a')| = 1
26 - 1 = 25
|ord('z') - ord('b')| = 24
26 - 24 = 2
|ord('a') - ord('z')| = 25
26 - 25 = 1
word
, since we process each letter once.