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 exactly1 button.
Each button maps to at most3 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 _theminimum number of keypresses needed to type _susing your keypad.
Note that the characters mapped to by each button, and the order they are mapped in cannot be changed.

Input: s ="apple"Output: 5Explanation: One optimal way to setup your keypad is shown above.Type 'a' by pressing button 1 once.Type 'p' by pressing button 6 once.Type 'p' by pressing button 6 once.Type 'l' by pressing button 5 once.Type 'e' by pressing button 3 once.A total of 5 button presses are needed, so return5.
Example 2:
1
2
3
4
5
6
7
8
9

Input: s ="abcdefghijkl"Output: 15Explanation: One optimal way to setup your keypad is shown above.The letters 'a' to 'i' can each be typed by pressing a button once.Type 'j' by pressing button 1 twice.Type 'k' by pressing button 2 twice.Type 'l' by pressing button 3 twice.A total of 15 button presses are needed, so return15.
#include<string>#include<vector>#include<algorithm>usingnamespace std;
classSolution {
public:int minimumKeypresses(string s) {
vector<int> freq(26, 0);
for (char c : s) freq[c-'a']++;
sort(freq.rbegin(), freq.rend());
int ans =0;
for (int i =0; i <26; ++i) {
ans += freq[i] * (i/9+1);
}
return ans;
}
};
import java.util.*;
classSolution {
publicintminimumKeypresses(String s) {
int[] freq =newint[26];
for (char c : s.toCharArray()) freq[c-'a']++;
Arrays.sort(freq);
int ans = 0;
for (int i = 0; i < 26; ++i) {
ans += freq[25-i]* (i/9 + 1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funminimumKeypresses(s: String): Int {
val freq = IntArray(26)
for (c in s) freq[c-'a']++ freq.sortDescending()
var ans = 0for (i in0 until 26) {
ans += freq[i] * (i/9 + 1)
}
return ans
}
}
1
2
3
4
5
6
classSolution:
defminimumKeypresses(self, s: str) -> int:
from collections import Counter
freq = sorted(Counter(s).values(), reverse=True)
freq += [0] * (26- len(freq))
return sum(freq[i] * (i//9+1) for i in range(26))
1
2
3
4
5
6
7
8
9
10
impl Solution {
pubfnminimum_keypresses(s: String) -> i32 {
letmut freq =vec![0; 26];
for c in s.chars() { freq[c asusize-'a'asusize] +=1; }
freq.sort_by(|a, b| b.cmp(a));
letmut ans =0;
for i in0..26 { ans += freq[i] * (i/9+1); }
ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
minimumKeypresses(s: string):number {
constfreq= Array(26).fill(0);
for (constcofs) freq[c.charCodeAt(0) -97]++;
freq.sort((a, b) =>b-a);
letans=0;
for (leti=0; i<26; ++i) ans+=freq[i] * (Math.floor(i/9) +1);
returnans;
}
}