| q | w | e | r | t | y | u | i | o | p |
| a | s | d | f | g | h | j | k | l | |
| z | x | c | v | b | n | m |
You are given a string s that consists of lowercase English letters only. Return an integer denoting the total distance to type s using only one finger. Your finger starts on the key 'a'.
The distance between two keys at (r1, c1) and (r2, c2) is |r1 - r2| + |c1 - c2|.
Example 1:
Input: s = "hello"
Output: 17
Explanation:
'a', which is at (1, 0).'h', which is at (1, 5). The distance is |1 - 1| + |0 - 5| = 5.'e', which is at (0, 2). The distance is |1 - 0| + |5 - 2| = 4.'l', which is at (1, 8). The distance is |0 - 1| + |2 - 8| = 7.'l', which is at (1, 8). The distance is |1 - 1| + |8 - 8| = 0.'o', which is at (0, 8). The distance is |1 - 0| + |8 - 8| = 1.5 + 4 + 7 + 0 + 1 = 17.Example 2:
Input: s = "a"
Output: 0
Explanation:
'a', which is at (1, 0).'a', which is at (1, 0). The distance is |1 - 1| + |0 - 0| = 0.
Constraints:
1 <= s.length <= 104s consists of lowercase English letters only.We define a hash table pos to store the position of each character on the keyboard. For each character in string s, we calculate the distance from the previous character to the current character and accumulate it to the answer. Finally, we return the answer.
The time complexity is O(n), where n is the length of string s. The space complexity is O(|\Sigma|), where \Sigma is the character set, which here is 26 lowercase English letters.
Java
C++
Go
TypeScript
Practice Total Distance to Type a String Using One Finger with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor