Leetcode 3120. Count the Number of Special Characters I
You are given a string s
and a set of special characters. Your task is to count the number of occurrences of these special characters in the string s
.
Return the count of special characters in the string.
s
and a Set<Character>
of special characters.s
be empty?
0
.0
.import java.util.Set;
public class SpecialCharacterCounter {
public int countSpecialCharacters(String s, Set<Character> specialCharacters) {
int count = 0;
for (char c : s.toCharArray()) {
if (specialCharacters.contains(c)) {
count++;
}
}
return count;
}
public static void main(String[] args) {
// Example usage:
SpecialCharacterCounter counter = new SpecialCharacterCounter();
String s = "example!string#with$special*characters";
Set<Character> specialCharacters = Set.of('!', '#', '$', '*');
System.out.println(counter.countSpecialCharacters(s, specialCharacters)); // Output: 4
}
}
O(n)
, where n
is the length of the string s
. This is because we need to iterate through each character in the string once.O(k)
, where k
is the number of special characters. The Set
itself and the internal workings such as the hash table for set membership checks are additional space which is relatively small compared to the string length.This solution efficiently counts the number of special characters in the given string using a straightforward approach and optimal complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?