You are given a string word
. A letter is called special if it appears both in lowercase and uppercase in word
. Return the number of special letters in word
.
LeetCode Problem - 3120
import java.util.*;
class Solution {
// Function to count the number of special characters
public int numberOfSpecialChars(String word) {
Map<Character, Integer> mp1 = new HashMap<>(); // Map to store uppercase letters frequency
for (int i = 0; i < word.length(); i++) { // Iterate over characters in the word
int hashCode = word.codePointAt(i); // Get the Unicode code point of the character
if (hashCode >= 65 && hashCode <= 90) { // If the character is uppercase
mp1.put(word.charAt(i), mp1.getOrDefault(word.charAt(i), 0) + 1); // Add to map with frequency
}
}
Map<Character, Integer> mp2 = new HashMap<>(); // Map to store lowercase letters frequency
for (int i = 0; i < word.length(); i++) { // Iterate over characters in the word
int hashCode = word.codePointAt(i); // Get the Unicode code point of the character
if (hashCode >= 97 && hashCode <= 122) { // If the character is lowercase
mp2.put(word.charAt(i), mp2.getOrDefault(word.charAt(i), 0) + 1); // Add to map with frequency
}
}
String capitalLetters = mp1.keySet().toString(); // Convert keys of mp1 to string
String smallLetters = mp2.keySet().toString(); // Convert keys of mp2 to string
int ans = 0; // Initialize counter for special characters
if (!mp1.isEmpty()) { // If mp1 is not empty
for (int i = 0; i < capitalLetters.length(); i++) { // Iterate over characters in capitalLetters
int currentHashCode = capitalLetters.codePointAt(i) + 32; // Get lowercase Unicode code point
for (int j = 0; j < smallLetters.length(); j++) { // Iterate over characters in smallLetters
if (currentHashCode == smallLetters.codePointAt(j)) { // If matching lowercase character found
ans++; // Increment special character count
}
}
}
}
return ans; // Return the count of special characters
}
}