[LeetCode] Minimum Number of Keypresses

2268. Minimum Number of Keypresses

You have a keypad with 9 buttons, numbered from 1 to 9, each mapped to lowercase English letters. You can choose which characters each button is matched to as long as:

  • All 26 lowercase English letters are mapped to.
  • Each character is mapped to by exactly 1 button.
  • Each button maps to at most 3 characters.

To type the first character matched to a button, you press the button once. To type the second character, you press the button twice, and so on.

Given a string s, return the minimum number of keypresses needed to type s using your keypad.

Note that the characters mapped to by each button, and the order they are mapped in cannot be changed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int minimumKeypresses(string s) {
unordered_map<char, int> counter;
for(auto& ch : s)
counter[ch]++;
vector<int> counts;
for(auto& [_, c] : counter)
counts.push_back(c);
sort(rbegin(counts), rend(counts));
int res = 0;
for(int i = 0; i < counts.size(); i++) {
res += counts[i] * ((i / 9) + 1);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/LeetCode/minimum-number-of-keypresses/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.