comments | difficulty | edit_url | rating | source | tags | ||
---|---|---|---|---|---|---|---|
true |
Easy |
1205 |
Weekly Contest 394 Q1 |
|
You are given a string word
. A letter is called special if it appears both in lowercase and uppercase in word
.
Return the number of special letters in word
.
Example 1:
Input: word = "aaAbcBC"
Output: 3
Explanation:
The special characters in word
are 'a'
, 'b'
, and 'c'
.
Example 2:
Input: word = "abc"
Output: 0
Explanation:
No character in word
appears in uppercase.
Example 3:
Input: word = "abBCab"
Output: 1
Explanation:
The only special character in word
is 'b'
.
Constraints:
1 <= word.length <= 50
word
consists of only lowercase and uppercase English letters.
We use a hash table or array
Finally, return the count of special characters.
The time complexity is
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))
class Solution {
public int numberOfSpecialChars(String word) {
boolean[] s = new boolean['z' + 1];
for (int i = 0; i < word.length(); ++i) {
s[word.charAt(i)] = true;
}
int ans = 0;
for (int i = 0; i < 26; ++i) {
if (s['a' + i] && s['A' + i]) {
++ans;
}
}
return ans;
}
}
class Solution {
public:
int numberOfSpecialChars(string word) {
vector<bool> s('z' + 1);
for (char& c : word) {
s[c] = true;
}
int ans = 0;
for (int i = 0; i < 26; ++i) {
ans += s['a' + i] && s['A' + i];
}
return ans;
}
};
func numberOfSpecialChars(word string) (ans int) {
s := make([]bool, 'z'+1)
for _, c := range word {
s[c] = true
}
for i := 0; i < 26; i++ {
if s['a'+i] && s['A'+i] {
ans++
}
}
return
}
function numberOfSpecialChars(word: string): number {
const s: boolean[] = Array.from({ length: 'z'.charCodeAt(0) + 1 }, () => false);
for (let i = 0; i < word.length; ++i) {
s[word.charCodeAt(i)] = true;
}
let ans: number = 0;
for (let i = 0; i < 26; ++i) {
if (s['a'.charCodeAt(0) + i] && s['A'.charCodeAt(0) + i]) {
++ans;
}
}
return ans;
}