LeetCode 题解工作台
统计特殊字母的数量 II
给你一个字符串 word 。如果 word 中同时出现某个字母 c 的小写形式和大写形式,并且 每个 小写形式的 c 都出现在第一个大写形式的 c 之前,则称字母 c 是一个 特殊字母 。 返回 word 中 特殊字母 的数量。 示例 1: 输入: word = "aaAbcBC" 输出: 3 解释…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · 哈希·表·结合·string
答案摘要
我们定义两个哈希表或数组 和 ,用于存储每个字母第一次出现的位置和最后一次出现的位置。 然后我们遍历字符串 ,更新 和 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 哈希·表·结合·string 题型思路
题目描述
给你一个字符串 word。如果 word 中同时出现某个字母 c 的小写形式和大写形式,并且 每个 小写形式的 c 都出现在第一个大写形式的 c 之前,则称字母 c 是一个 特殊字母 。
返回 word 中 特殊字母 的数量。
示例 1:
输入:word = "aaAbcBC"
输出:3
解释:
特殊字母是 'a'、'b' 和 'c'。
示例 2:
输入:word = "abc"
输出:0
解释:
word 中不存在特殊字母。
示例 3:
输入:word = "AbBCab"
输出:0
解释:
word 中不存在特殊字母。
提示:
1 <= word.length <= 2 * 105word仅由小写和大写英文字母组成。
解题思路
方法一:哈希表或数组
我们定义两个哈希表或数组 和 ,用于存储每个字母第一次出现的位置和最后一次出现的位置。
然后我们遍历字符串 ,更新 和 。
最后我们遍历所有的小写字母和大写字母,如果 存在且 存在且 ,则说明字母 是一个特殊字母,将答案加一。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度;而 为字符集大小,本题中 。
class Solution:
def numberOfSpecialChars(self, word: str) -> int:
first, last = {}, {}
for i, c in enumerate(word):
if c not in first:
first[c] = i
last[c] = i
return sum(
a in last and b in first and last[a] < first[b]
for a, b in zip(ascii_lowercase, ascii_uppercase)
)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for an efficient solution that minimizes both time and space complexity using hash tables.
- question_mark
Ensure the candidate recognizes the need for two passes or a similar approach to process both lowercase and uppercase occurrences.
- question_mark
Evaluate whether the candidate can effectively balance clarity and optimization in their approach.
常见陷阱
外企场景- error
Failing to account for the proper order of lowercase and uppercase occurrences can lead to incorrect results.
- error
Using an inefficient solution that does not utilize a hash table to track positions properly.
- error
Not considering edge cases, such as strings with no special characters or strings where characters appear only in one case.
进阶变体
外企场景- arrow_right_alt
Extend the problem to include numbers or other special characters.
- arrow_right_alt
Add a constraint to allow only specific subsets of characters (e.g., only letters A-Z, or only lowercase).
- arrow_right_alt
Consider optimizing space usage by using a more space-efficient data structure instead of a hash table.