-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid_palindrome.cc
More file actions
36 lines (29 loc) · 1.02 KB
/
valid_palindrome.cc
File metadata and controls
36 lines (29 loc) · 1.02 KB
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
36
#include "valid_palindrome.h"
#include <algorithm>
#include <cctype>
#include <string>
bool isPalindrome(const std::string &str) {
int left = 0;
int right = static_cast<int>(str.size()) - 1;
// Create a copy of the string and transform to lowercase
std::string lowerStr = str;
std::ranges::transform(lowerStr, lowerStr.begin(),
[](unsigned char character) { return std::tolower(character); });
while (left < right) {
// Move left pointer to the next alphanumeric character
while (left < right && std::isalnum(lowerStr[left]) == 0) {
++left;
}
// Move right pointer to the previous alphanumeric character
while (left < right && std::isalnum(lowerStr[right]) == 0) {
--right;
}
// Compare characters at left and right pointers
if (lowerStr[left] != lowerStr[right]) {
return false; // Not a palindrome
}
++left;
--right;
}
return true; // Is a palindrome
}