LeetCode 题解工作台

按键变更的次数

给你一个下标从 0 开始的字符串 s ,该字符串由用户输入。按键变更的定义是:使用与上次使用的按键不同的键。例如 s = "ab" 表示按键变更一次,而 s = "bBBb" 不存在按键变更。 返回用户输入过程中按键变更的次数。 注意: shift 或 caps lock 等修饰键不计入按键变更,也…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · String-driven solution strategy

bolt

答案摘要

我们可以遍历字符串,每次判断当前字符的小写形式是否与前一个字符的小写形式相同,如果不同则说明发生了按键变更,将答案加一即可。 时间复杂度 ,其中 是字符串 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 String-driven solution strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个下标从 0 开始的字符串 s ,该字符串由用户输入。按键变更的定义是:使用与上次使用的按键不同的键。例如 s = "ab" 表示按键变更一次,而 s = "bBBb" 不存在按键变更。

返回用户输入过程中按键变更的次数。

注意:shiftcaps 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 <= 100
  • s 仅由英文大写字母和小写字母组成。
lightbulb

解题思路

方法一:一次遍历

我们可以遍历字符串,每次判断当前字符的小写形式是否与前一个字符的小写形式相同,如果不同则说明发生了按键变更,将答案加一即可。

时间复杂度 O(n)O(n),其中 nn 是字符串 ss 的长度。空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def countKeyChanges(self, s: str) -> int:
        return sum(a != b for a, b in pairwise(s.lower()))
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

按键变更的次数题解:String-driven solution … | LeetCode #3019 简单