LeetCode 题解工作台
统计特殊字母的数量 I
给你一个字符串 word 。如果 word 中同时存在某个字母的小写形式和大写形式,则称这个字母为 特殊字母 。 返回 word 中 特殊字母 的数量。 示例 1: 输入: word = "aaAbcBC" 输出: 3 解释: word 中的特殊字母是 'a' 、 'b' 和 'c' 。 示例 2:…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 哈希·表·结合·string
答案摘要
我们用一个哈希表或数组 来记录字符串 中出现的字符。然后遍历 个字母,如果小写字母和大写字母都在 中出现,则特殊字符的数量加一。 最后返回特殊字符的数量即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你一个字符串 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 <= 50word仅由小写和大写英文字母组成。
解题思路
方法一:哈希表或数组
我们用一个哈希表或数组 来记录字符串 中出现的字符。然后遍历 个字母,如果小写字母和大写字母都在 中出现,则特殊字符的数量加一。
最后返回特殊字符的数量即可。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度;而 为字符集大小,本题中 。
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))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.