[LeetCode] Count the Number of Special Characters II

3121. Count the Number of Special Characters II

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int numberOfSpecialChars(string word) {
vector<int> lo(26,-1), hi(26,-1);
for(int i = 0; i < word.size(); i++) {
if(islower(word[i])) {
lo[word[i]-'a'] = i;
}
}
for(int i = word.size() - 1; i >= 0; i--) {
if(isupper(word[i])) {
hi[word[i]-'A'] = i;
}
}
int res = 0;
for(int i = 0; i < 26; i++) {
if(lo[i] == -1 or hi[i] == -1) continue;
if(lo[i] > hi[i]) continue;
res++;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/04/21/PS/LeetCode/count-the-number-of-special-characters-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.