3121. Count the Number of Special Characters II
🧩 Problem:
3121. Count the Number of Special Characters II
🧩 Problem:
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.
Constraints:
1 <= word.length <= 2 * 105wordconsists of only lowercase and uppercase English letters.
🔑 Key Idea:
👉 Store last lowercase index and first uppercase index; a letter is special if lowercase appears before uppercase.
✅ Solution:
class Solution {
public int numberOfSpecialChars(String word) {
int[] lower = new int[26];
int[] upper = new int[26];
Arrays.fill(lower, -1);
Arrays.fill(upper, -1);
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (ch >= ‘a’ && ch <= ‘z’) {
// Track the last occurrence of each lowercase letter
lower[ch — ‘a’] = i;
} else {
// Track the first occurrence of each uppercase letter
if (upper[ch — ‘A’] == -1)
upper[ch — ‘A’] = i;
}
}
int count = 0;
for (int i = 0; i < 26; i++) {
if (lower[i] != -1 && upper[i] != -1 && lower[i] < upper[i])
count++;
}
return count;
}
}
메타데이터
- post_id
- 8effe0728007
- slug
- 3121-count-the-number-of-special-characters-ii-8effe0728007
- url
- https://medium.com/@sarawrites/3121-count-the-number-of-special-characters-ii-8effe0728007
- canonical_url
- https://medium.com/@sarawrites/3121-count-the-number-of-special-characters-ii-8effe0728007
- author_url
- https://medium.com/@sarawrites
- status
- ok
- fetched_at
- 2026-06-09 15:37:30