Leetcode 3120. Count the Number of Special Characters I
You are given a string s. Count the number of special characters in the string. Special characters are defined as characters that are not alphanumeric (i.e., they are neither letters nor numbers).
s.isalnum function from the C++ standard library.Here’s the implementation in C++:
#include <iostream>
#include <cctype>
int countSpecialCharacters(const std::string& s) {
int count = 0;
for (char ch : s) {
if (!isalnum(ch)) {
count++;
}
}
return count;
}
int main() {
std::string s = "Hello, World! 123"; // Example input
std::cout << "Number of special characters: " << countSpecialCharacters(s) << std::endl;
return 0;
}
isalnum function: This function checks if the character is alphanumeric. If isalnum returns false, then the character is a special character.for loop: Iterate through each character in the string.count variable: Tracks the number of special characters encountered.if (!isalnum(ch)): Increment the counter count if the character is not alphanumeric.The time complexity of this solution is O(n), where n is the length of the input string s. This is because the algorithm involves a single pass through the string, performing a constant-time check for each character.
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?