/**
* Problem: LeetCode 3121 - Count the Number of Special Characters II
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
import java.util.Arrays;
class Solution {
public int numberOfSpecialChars(String word) {
int[] lastLower = new int[26];
int[] firstUpper = new int[26];
Arrays.fill(lastLower, -1);
Arrays.fill(firstUpper, -1);
int n = word.length();
for (int i = 0; i < n; i++) {
char ch = word.charAt(i);
if (ch >= 'a' && ch <= 'z') {
lastLower[ch - 'a'] = i;
} else if (ch >= 'A' && ch <= 'Z') {
int idx = ch - 'A';
if (firstUpper[idx] == -1) {
firstUpper[idx] = i;
}
}
}
int specialCount = 0;
for (int i = 0; i < 26; i++) {
if (lastLower[i] != -1 && firstUpper[i] != -1 && lastLower[i] < firstUpper[i]) {
specialCount++;
}
}
return specialCount;
}
}
"""
Problem: LeetCode 3121 - Count the Number of Special Characters II
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
class Solution:
def numberOfSpecialChars(self, word: str) -> int:
last_lower = [-1] * 26
first_upper = [-1] * 26
for i, ch in enumerate(word):
if 'a' <= ch <= 'z':
last_lower[ord(ch) - ord('a')] = i
elif 'A' <= ch <= 'Z':
idx = ord(ch) - ord('A')
if first_upper[idx] == -1:
first_upper[idx] = i
special_count = 0
for i in range(26):
if last_lower[i] != -1 and first_upper[i] != -1 and last_lower[i] < first_upper[i]:
special_count += 1
return special_count
/**
* Problem: LeetCode 3121 - Count the Number of Special Characters II
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
int numberOfSpecialChars(string word) {
vector<int> lastLower(26, -1);
vector<int> firstUpper(26, -1);
int n = word.size();
for (int i = 0; i < n; i++) {
char ch = word[i];
if (ch >= 'a' && ch <= 'z') {
lastLower[ch - 'a'] = i;
} else if (ch >= 'A' && ch <= 'Z') {
int idx = ch - 'A';
if (firstUpper[idx] == -1) {
firstUpper[idx] = i;
}
}
}
int specialCount = 0;
for (int i = 0; i < 26; i++) {
if (lastLower[i] != -1 && firstUpper[i] != -1 && lastLower[i] < firstUpper[i]) {
specialCount++;
}
}
return specialCount;
}
};
/**
* Problem: LeetCode 3121 - Count the Number of Special Characters II
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
/**
* @param {string} word
* @return {number}
*/
var numberOfSpecialChars = function(word) {
const lastLower = new Int32Array(26).fill(-1);
const firstUpper = new Int32Array(26).fill(-1);
const n = word.length;
for (let i = 0; i < n; i++) {
const code = word.charCodeAt(i);
if (code >= 97 && code <= 122) { // 'a' - 'z'
lastLower[code - 97] = i;
} else if (code >= 65 && code <= 90) { // 'A' - 'Z'
const idx = code - 65;
if (firstUpper[idx] === -1) {
firstUpper[idx] = i;
}
}
}
let specialCount = 0;
for (let i = 0; i < 26; i++) {
if (lastLower[i] !== -1 && firstUpper[i] !== -1 && lastLower[i] < firstUpper[i]) {
specialCount++;
}
}
return specialCount;
};