[LeetCode]#1974. Minimum Time to Type Word Using Special Typewriter
2 min readNov 25, 2021
Environment: Python 3.8
Key technique: ord, for, if
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.
Analysis:
- if move <13, go clockwise. Else, go counterclockwise.
- Add one second for type.
- Summary all second
Solution:
class Solution:
def minTimeToType(self, word):
s=0
now='a'
for i in range(len(word)):
move=abs(ord(word[i])-ord(now))
if move > 13:
move= 26 -move
s+=(move+1)
now=word[i]
return s
Submissions:
Reference: