[LeetCode] Single-Row Keyboard

1165. Single-Row Keyboard

There is a special keyboard with all keys in a single row.

Given a string keyboard of length 26 indicating the layout of the keyboard (indexed from 0 to 25), initially your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken to move your finger from index i to index j is |i - j|.

You want to type a string word. Write a function to calculate how much time it takes to type it with one finger.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int calculateTime(string keyboard, string word) {
map<char, int> keyIndex;
for(int i = 0; i < keyboard.length(); ++i) {
keyIndex[keyboard[i]] = i;
}

int finger = 0;
int res = 0;
for(int i = 0; i < word.length(); ++i) {
res += abs(keyIndex[word[i]] - finger);
finger = keyIndex[word[i]];
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/01/PS/LeetCode/single-row-keyboard/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.