Problem of The Day: MMinimum Time to Type Word Using Special Typewriter
2 min read
400 words
Problem Statement
Solution [accepted]
class Solution:
def minTimeToType(self, word: str) -> int:
res = 0
ptr = 0
for c in word:
res += 1
idx = ord(c) - ord('a')
if idx == ptr:
continue
clockwise = (ptr - idx) % 26
counterClockwise = -(ptr-idx) % 26
res += min(clockwise, counterClockwise)
ptr = idx
return res
Optimize code
# Python
class Solution:
def minTimeToType(self, word: str) -> int:
time = 0
ptr = 0 # 'a' -> 0
for c in word:
idx = ord(c) - ord('a')
d = abs(ptr - idx)
time += min(d, 26 - d) + 1 # move + press
ptr = idx
return time
public class Solution {
public int MinTimeToType(string word) {
int time = 0;
int ptr = 0;
foreach (var c in word) {
var idx = c - 'a';
var dist = Math.Abs(ptr - idx);
time += Math.Min(dist, 26 - dist) + 1;
ptr = idx;
}
return time;
}
}
Leave a comment