LeetCode 题解工作台
按键变更的次数
给你一个下标从 0 开始的字符串 s ,该字符串由用户输入。按键变更的定义是:使用与上次使用的按键不同的键。例如 s = "ab" 表示按键变更一次,而 s = "bBBb" 不存在按键变更。 返回用户输入过程中按键变更的次数。 注意: shift 或 caps lock 等修饰键不计入按键变更,也…
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · String-driven solution strategy
答案摘要
我们可以遍历字符串,每次判断当前字符的小写形式是否与前一个字符的小写形式相同,如果不同则说明发生了按键变更,将答案加一即可。 时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路
题目描述
给你一个下标从 0 开始的字符串 s ,该字符串由用户输入。按键变更的定义是:使用与上次使用的按键不同的键。例如 s = "ab" 表示按键变更一次,而 s = "bBBb" 不存在按键变更。
返回用户输入过程中按键变更的次数。
注意:shift 或 caps lock 等修饰键不计入按键变更,也就是说,如果用户先输入字母 'a' 然后输入字母 'A' ,不算作按键变更。
示例 1:
输入:s = "aAbBcC" 输出:2 解释: 从 s[0] = 'a' 到 s[1] = 'A',不存在按键变更,因为不计入 caps lock 或 shift 。 从 s[1] = 'A' 到 s[2] = 'b',按键变更。 从 s[2] = 'b' 到 s[3] = 'B',不存在按键变更,因为不计入 caps lock 或 shift 。 从 s[3] = 'B' 到 s[4] = 'c',按键变更。 从 s[4] = 'c' 到 s[5] = 'C',不存在按键变更,因为不计入 caps lock 或 shift 。
示例 2:
输入:s = "AaAaAaaA" 输出:0 解释: 不存在按键变更,因为这个过程中只按下字母 'a' 和 'A' ,不需要进行按键变更。
提示:
1 <= s.length <= 100s仅由英文大写字母和小写字母组成。
解题思路
方法一:一次遍历
我们可以遍历字符串,每次判断当前字符的小写形式是否与前一个字符的小写形式相同,如果不同则说明发生了按键变更,将答案加一即可。
时间复杂度 ,其中 是字符串 的长度。空间复杂度 。
class Solution:
def countKeyChanges(self, s: str) -> int:
return sum(a != b for a, b in pairwise(s.lower()))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because we traverse the string once. Space complexity is O(1) if we modify in place or O(n) if creating a lowercase copy. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expecting an O(n) string traversal solution using simple comparisons.
- question_mark
Checking for correct handling of uppercase and lowercase letters as the same key.
- question_mark
Looking for clarity in defining what counts as a key change.
常见陷阱
外企场景- error
Counting changes when only the letter case differs, which is not a key change.
- error
Forgetting to compare each character with the previous one after normalization.
- error
Returning the length minus one or other off-by-one errors in counting changes.
进阶变体
外企场景- arrow_right_alt
Count key changes including numeric and symbol keys, still ignoring modifiers.
- arrow_right_alt
Track positions of each key change along with the count.
- arrow_right_alt
Consider key changes only for consecutive different letters ignoring vowels or consonants.