You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/2200-2299/2268.Minimum Number of Keypresses/README_EN.md
+57-26
Original file line number
Diff line number
Diff line change
@@ -76,7 +76,15 @@ A total of 15 button presses are needed, so return 15.
76
76
77
77
<!-- solution:start -->
78
78
79
-
### Solution 1
79
+
### Solution 1: Counting + Greedy
80
+
81
+
First, we count the occurrence of each character in the string $s$, and record it in an array or hash table $\textit{cnt}$.
82
+
83
+
The problem requires minimizing the number of key presses, so the $9$ most frequent characters should correspond to keys $1$ to $9$, the $10$th to $18$th most frequent characters should correspond to keys $1$ to $9$ again, and so on.
84
+
85
+
Therefore, we can sort the values in $\textit{cnt}$ in descending order, and then allocate them to the keys in the order from $1$ to $9$, adding $1$ to the number of key presses after allocating every $9$ characters.
86
+
87
+
The time complexity is $O(n + |\Sigma| \times \log |\Sigma|)$, and the space complexity is $O(|\Sigma|)$. Here, $n$ is the length of the string $s$, and $\Sigma$ is the set of characters appearing in the string $s$. In this problem, $\Sigma$ is the set of lowercase letters, so $|\Sigma| = 26$.
80
88
81
89
<!-- tabs:start -->
82
90
@@ -86,13 +94,11 @@ A total of 15 button presses are needed, so return 15.
86
94
classSolution:
87
95
defminimumKeypresses(self, s: str) -> int:
88
96
cnt = Counter(s)
89
-
ans =0
90
-
i, j =0, 1
91
-
for v insorted(cnt.values(), reverse=True):
92
-
i +=1
93
-
ans += j * v
97
+
ans, k =0, 1
98
+
for i, x inenumerate(sorted(cnt.values(), reverse=True), 1):
0 commit comments