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.
A letter is special if both its lowercase and uppercase forms appear, and all lowercase occurrences come before the first uppercase occurrence. We can track the last index of each lowercase and the first index of each uppercase, then check the order.
classSolution {
publicintnumberOfSpecialChars(String word) {
int[] lastLower =newint[26];
int[] firstUpper =newint[26];
Arrays.fill(lastLower, -1);
Arrays.fill(firstUpper, -1);
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (Character.isLowerCase(c)) lastLower[c -'a']= i;
elseif (Character.isUpperCase(c) && firstUpper[c -'A']==-1) firstUpper[c -'A']= i;
}
int ans = 0;
for (int i = 0; i < 26; i++) {
if (lastLower[i]!=-1 && firstUpper[i]!=-1 && lastLower[i]< firstUpper[i]) ans++;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution {
funnumberOfSpecialChars(word: String): Int {
val lastLower = IntArray(26) { -1 }
val firstUpper = IntArray(26) { -1 }
for ((i, c) in word.withIndex()) {
if (c.isLowerCase()) lastLower[c - 'a'] = i
elseif (c.isUpperCase() && firstUpper[c - 'A'] == -1) firstUpper[c - 'A'] = i
}
var ans = 0for (i in0 until 26) {
if (lastLower[i] != -1&& firstUpper[i] != -1&& lastLower[i] < firstUpper[i]) ans++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defnumberOfSpecialChars(self, word: str) -> int:
last_lower = [-1] *26 first_upper = [-1] *26for i, c in enumerate(word):
if c.islower():
last_lower[ord(c) - ord('a')] = i
elif c.isupper() and first_upper[ord(c) - ord('A')] ==-1:
first_upper[ord(c) - ord('A')] = i
ans =0for i in range(26):
if last_lower[i] !=-1and first_upper[i] !=-1and last_lower[i] < first_upper[i]:
ans +=1return ans