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.
思路:每个单词type需要1second,转动转盘需要1second,怎么转动,就是看Math.abs(diff), 26-diff的最小值;
class Solution {
public int minTimeToType(String word) {
int count = word.length();
char pre = 'a';
for(int i = 0; i < word.length(); i++) {
char cur = word.charAt(i);
int diff = Math.abs(cur - pre);
diff = Math.min(diff, 26 - diff);
count += diff;
pre = cur;
}
return count;
}
}