A letter is special if both its lowercase and uppercase forms appear in the string. We can use sets to track which lowercase and uppercase letters are present, then count how many letters appear in both forms.
classSolution {
public:int numberOfSpecialChars(string word) {
unordered_set<char> lower, upper;
for (char c : word) {
if (islower(c)) lower.insert(c);
elseif (isupper(c)) upper.insert(c);
}
int ans =0;
for (char c ='a'; c <='z'; ++c) {
if (lower.count(c) && upper.count(c -'a'+'A')) ++ans;
}
return ans;
}
};
classSolution {
publicintnumberOfSpecialChars(String word) {
Set<Character> lower =new HashSet<>();
Set<Character> upper =new HashSet<>();
for (char c : word.toCharArray()) {
if (Character.isLowerCase(c)) lower.add(c);
elseif (Character.isUpperCase(c)) upper.add(c);
}
int ans = 0;
for (char c ='a'; c <='z'; ++c) {
if (lower.contains(c) && upper.contains((char)(c -'a'+'A'))) ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funnumberOfSpecialChars(word: String): Int {
val lower = mutableSetOf<Char>()
val upper = mutableSetOf<Char>()
for (c in word) {
if (c.isLowerCase()) lower.add(c)
elseif (c.isUpperCase()) upper.add(c)
}
var ans = 0for (c in'a'..'z') {
if (lower.contains(c) && upper.contains(c.uppercaseChar())) ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defnumberOfSpecialChars(self, word: str) -> int:
lower: set[str] = set()
upper: set[str] = set()
for c in word:
if c.islower():
lower.add(c)
elif c.isupper():
upper.add(c)
ans =0for i in range(26):
ch = chr(ord('a') + i)
if ch in lower and ch.upper() in upper:
ans +=1return ans