LeetCode 题解工作台

统计特殊字母的数量 I

给你一个字符串 word 。如果 word 中同时存在某个字母的小写形式和大写形式,则称这个字母为 特殊字母 。 返回 word 中 特殊字母 的数量。 示例 1: 输入: word = "aaAbcBC" 输出: 3 解释: word 中的特殊字母是 'a' 、 'b' 和 'c' 。 示例 2:…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 哈希·表·结合·string

bolt

答案摘要

我们用一个哈希表或数组 来记录字符串 中出现的字符。然后遍历 个字母,如果小写字母和大写字母都在 中出现,则特殊字符的数量加一。 最后返回特殊字符的数量即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个字符串 word。如果 word 中同时存在某个字母的小写形式和大写形式,则称这个字母为 特殊字母

返回 word 特殊字母 的数量。

 

示例 1:

输入:word = "aaAbcBC"

输出:3

解释:

word 中的特殊字母是 'a''b''c'

示例 2:

输入:word = "abc"

输出:0

解释:

word 中不存在大小写形式同时出现的字母。

示例 3:

输入:word = "abBCab"

输出:1

解释:

word 中唯一的特殊字母是 'b'

 

提示:

  • 1 <= word.length <= 50
  • word 仅由小写和大写英文字母组成。
lightbulb

解题思路

方法一:哈希表或数组

我们用一个哈希表或数组 ss 来记录字符串 wordword 中出现的字符。然后遍历 2626 个字母,如果小写字母和大写字母都在 ss 中出现,则特殊字符的数量加一。

最后返回特殊字符的数量即可。

时间复杂度 O(n+Σ)O(n + |\Sigma|),空间复杂度 O(Σ)O(|\Sigma|)。其中 nn 为字符串 wordword 的长度;而 Σ|\Sigma| 为字符集大小,本题中 Σ128|\Sigma| \leq 128

1
2
3
4
5
class Solution:
    def numberOfSpecialChars(self, word: str) -> int:
        s = set(word)
        return sum(a in s and b in s for a, b in zip(ascii_lowercase, ascii_uppercase))
speed

复杂度分析

指标
时间complexity depends on the approach. The hash table approach is O(n), where n is the length of the string. The brute force method is O(n^2), and the set-based approach also works in O(n), making it efficient for the given constraints. Space complexity is O(1) for the hash table or sets, as the size is limited to the 26 characters in each case.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Focus on solving the problem efficiently within the given constraints.

  • question_mark

    A correct approach with a hash table will demonstrate the ability to optimize with space and time.

  • question_mark

    Look for the candidate's ability to handle edge cases like strings with no uppercase characters.

warning

常见陷阱

外企场景
  • error

    Over-complicating the solution with unnecessary passes through the string.

  • error

    Ignoring edge cases, such as when there are no special characters or when the string is very short.

  • error

    Using inefficient data structures that may lead to excessive time complexity.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Change the input string to include digits or special characters and see if the solution adapts.

  • arrow_right_alt

    Increase the string length to test the performance of the algorithm.

  • arrow_right_alt

    Test the solution with uppercase and lowercase characters mixed in various sequences.

help

常见问题

外企场景

统计特殊字母的数量 I题解:哈希·表·结合·string | LeetCode #3120 简单