Description
You are given a string word. A letter c is called special if it appears both in lowercase and uppercase in word, and every lowercase occurrence of c appears before the first uppercase occurrence of c.
Return the number of special letters in word.
Example 1:
Input: word = "aaAbcBC"
Output: 3
Explanation:
The special characters are 'a', 'b', and 'c'.
Example 2:
Input: word = "abc"
Output: 0
Explanation:
There are no special characters in word.
Example 3:
Input: word = "AbBCab"
Output: 0
Explanation:
There are no special characters in word.
Constraints:
1 <= word.length <= 2 * 105wordconsists of only lowercase and uppercase English letters.
Solutions
This solution follows the same array-based approach as the previous version, using a 52-element array to track character positions with adjusted offset calculations. It stores the first lowercase position or first uppercase position and checks the inverse condition compared to the second solution. It counts letters where the lowercase character appears before its corresponding uppercase counterpart, making it a different interpretation of the "special character" requirement.
/**
* @param {string} word
* @return {number}
*/
var numberOfSpecialChars = function(word) {
const arr = new Array(52).fill(-1);
for (let i = 0; i < word.length; i++) {
const code = word.charCodeAt(i);
const isLowerCase = code >= 97;
const pos = code - (isLowerCase ? 97 : 39);
if (isLowerCase || arr[pos] === -1) {
arr[pos] = i;
}
}
let res = 0;
for (let i = 0; i < 26; i++) {
if (arr[i] > -1 && arr[i] < arr[26 + i]) {
res++;
}
}
return res;
};