LeetCode 题解工作台
输入单词需要的最少按键次数 II
给你一个字符串 word ,由小写英文字母组成。 电话键盘上的按键与 不同 小写英文字母集合相映射,可以通过按压按键来组成单词。例如,按键 2 对应 ["a","b","c"] ,我们需要按一次键来输入 "a" ,按两次键来输入 "b" ,按三次键来输入 "c" 。 现在允许你将编号为 2 到 9 …
5
题型
6
代码语言
3
相关题
当前训练重点
中等 · 贪心·invariant
答案摘要
我们用一个哈希表或数组 统计字符串 中每个字母出现的次数。接下来,按照字母出现的次数从大到小排序,然后每 个字母一组,将每组中的字母分配到 个按键上。 时间复杂度 $O(n + |\Sigma| \times \log |\Sigma|)$,空间复杂度 。其中 是字符串 的长度,而 是字符串 中出现的字母集合。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个字符串 word,由小写英文字母组成。
电话键盘上的按键与 不同 小写英文字母集合相映射,可以通过按压按键来组成单词。例如,按键 2 对应 ["a","b","c"],我们需要按一次键来输入 "a",按两次键来输入 "b",按三次键来输入 "c"。
现在允许你将编号为 2 到 9 的按键重新映射到 不同 字母集合。每个按键可以映射到 任意数量 的字母,但每个字母 必须 恰好 映射到 一个 按键上。你需要找到输入字符串 word 所需的 最少 按键次数。
返回重新映射按键后输入 word 所需的 最少 按键次数。
下面给出了一种电话键盘上字母到按键的映射作为示例。注意 1,*,# 和 0 不 对应任何字母。
示例 1:
输入:word = "abcde" 输出:5 解释:图片中给出的重新映射方案的输入成本最小。 "a" -> 在按键 2 上按一次 "b" -> 在按键 3 上按一次 "c" -> 在按键 4 上按一次 "d" -> 在按键 5 上按一次 "e" -> 在按键 6 上按一次 总成本为 1 + 1 + 1 + 1 + 1 = 5 。 可以证明不存在其他成本更低的映射方案。
示例 2:
输入:word = "xyzxyzxyzxyz" 输出:12 解释:图片中给出的重新映射方案的输入成本最小。 "x" -> 在按键 2 上按一次 "y" -> 在按键 3 上按一次 "z" -> 在按键 4 上按一次 总成本为 1 * 4 + 1 * 4 + 1 * 4 = 12 。 可以证明不存在其他成本更低的映射方案。 注意按键 9 没有映射到任何字母:不必让每个按键都存在与之映射的字母,但是每个字母都必须映射到按键上。
示例 3:
输入:word = "aabbccddeeffgghhiiiiii" 输出:24 解释:图片中给出的重新映射方案的输入成本最小。 "a" -> 在按键 2 上按一次 "b" -> 在按键 3 上按一次 "c" -> 在按键 4 上按一次 "d" -> 在按键 5 上按一次 "e" -> 在按键 6 上按一次 "f" -> 在按键 7 上按一次 "g" -> 在按键 8 上按一次 "h" -> 在按键 9 上按两次 "i" -> 在按键 9 上按一次 总成本为 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 1 * 2 + 2 * 2 + 6 * 1 = 24 。 可以证明不存在其他成本更低的映射方案。
提示:
1 <= word.length <= 105word仅由小写英文字母组成。
解题思路
方法一:贪心 + 排序
我们用一个哈希表或数组 统计字符串 中每个字母出现的次数。接下来,按照字母出现的次数从大到小排序,然后每 个字母一组,将每组中的字母分配到 个按键上。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度,而 是字符串 中出现的字母集合。
class Solution:
def minimumPushes(self, word: str) -> int:
cnt = Counter(word)
ans = 0
for i, x in enumerate(sorted(cnt.values(), reverse=True)):
ans += (i // 8 + 1) * x
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates an understanding of greedy algorithms and is able to explain the trade-offs of greedy choices.
- question_mark
The candidate efficiently identifies the mapping strategy and can explain why certain letters should be grouped with fewer presses.
- question_mark
The candidate handles the edge cases well, including cases with repetitive characters or the largest possible word length.
常见陷阱
外企场景- error
Failing to correctly count the frequency of letters, leading to incorrect mappings.
- error
Misunderstanding how to distribute letters across keys, which can result in suboptimal mappings.
- error
Not recognizing that keys can be left unmapped, potentially overcomplicating the solution.
进阶变体
外企场景- arrow_right_alt
Implementing the solution for a fixed set of key mappings instead of remapping the keys.
- arrow_right_alt
Applying the greedy approach to a keypad with a different number of keys.
- arrow_right_alt
Adapting the problem to work with uppercase letters or other alphabets.