3120. Count the Number of Special Characters I
Description
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 <= 50wordconsists of only lowercase and uppercase English letters.
Solutions
Solution 1: Hash Table or Array
Thinking
A letter is special when both cases appear. Scanning the string once per letter repeats \(O(n|\Sigma|)\) work.
Membership of each character is enough, and a set built in one pass answers all \(26\) pairs.
Insert \(word\) into a set, then count letters whose lower and upper forms both occur.
We use a hash table or array \(s\) to record the characters that appear in the string \(word\). Then we traverse the 26 letters. If both the lowercase and uppercase letters appear in \(s\), the count of special characters is incremented by one.
Finally, return the count of special characters.
The time complexity is \(O(n + |\Sigma|)\), and the space complexity is \(O(|\Sigma|)\). Where \(n\) is the length of the string \(word\), and \(|\Sigma|\) is the size of the character set. In this problem, \(|\Sigma| \leq 128\).
1 2 3 4 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |