目标
给你一个字符串 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 仅由小写和大写英文字母组成。
思路
有一个字符串 word,返回其中大小写同时存在的的字母个数。
使用哈希表记录已经出现的字母,如果已经同时出现过大小写,需要跳过,避免重复计数。否则,如果当前字母是小写,判断对应大写是否在哈希表中,如果当前字母是大写,判断对应小写是否在哈希表中,将当前字母加入哈希表。
代码
/**
* @date 2026-05-26 8:51
*/
public class NumberOfSpecialChars3120 {
public int numberOfSpecialChars(String word) {
Set<Character> set = new HashSet<>();
int n = word.length();
int res = 0;
for (int i = 0; i < n; i++) {
char c = word.charAt(i);
if (set.contains(c) && (set.contains((char) (c + 32)) || set.contains((char) (c - 32)))) {
continue;
}
if ((c < 'a' && set.contains((char) (c + 32))) || (c >= 'a' && set.contains((char) (c - 32)))) {
res++;
}
set.add(c);
}
return res;
}
}
性能









