1190. Multi-Tap Presses
An old phone keypad has the letters 2=abc, 3=def, 4=ghi, 5=jkl, 6=mno, 7=pqrs, 8=tuv and 9=wxyz. To type a letter you press its key as many times as the letter's 1-based position on that key, so c needs 3 presses and s needs 4. A space costs 1 press of key 0.
The phone needs a short pause whenever two consecutive letters sit on the same key, and typing the pause costs 1 extra press. A pause is added for a letter only if the character immediately before it is a letter on the same key; a space in between resets this. Given message, return the total number of presses.
Constraints: 1 <= message.length <= 10^4 and message holds lowercase letters and spaces. A single pass with a lookup table runs in O(n) time and O(1) space.
Example 1
- Input:
- message = "abc"
- Output:
- 8
- Explanation:
Letters a, b, c all sit on key 2 at positions 1, 2, 3 (6 presses) and b and c each follow a letter on the same key, adding 2 pauses: 8.
Example 2
- Input:
- message = "hi me"
- Output:
- 10
- Explanation:
h is 2 presses and i is 3 on key 4 plus 1 pause, the space is 1, m is 1 and e is 2: 2+3+1+1+1+2 = 10.
Constraints
1 ≤ message.length ≤ 104
lowercase letters and spaces
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1)