-
Notifications
You must be signed in to change notification settings - Fork 0
/
palindromes.cpp
35 lines (29 loc) · 1.02 KB
/
palindromes.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
#include <cctype> // For std::isalnum and std::tolower
#include <algorithm> // For std::reverse
// Function to check if a string is a palindrome
bool isPalindrome(const std::string& str) {
std::string normalizedStr;
// Normalize the string: convert to lowercase and remove non-alphanumeric characters
for (char ch : str) {
if (std::isalnum(ch)) {
normalizedStr += std::tolower(ch);
}
}
// Reverse the normalized string
std::string reversedStr = normalizedStr;
std::reverse(reversedStr.begin(), reversedStr.end());
// Compare the normalized and reversed strings
return normalizedStr == reversedStr;
}
// Example usage
int main() {
std::string testStr = "A man, a plan, a canal, Panama";
if (isPalindrome(testStr)) {
std::cout << "\"" << testStr << "\" is a palindrome." << std::endl;
} else {
std::cout << "\"" << testStr << "\" is not a palindrome." << std::endl;
}
return 0;
}