Cover image for Interview Classic 150 Questions P125 Valid Palindrome

Interview Classic 150 Questions P125 Valid Palindrome


Timeline

timeline

2025-10-17

init

string

Title:

Using two pointers is definitely faster, but here we directly use the standard library’s reverse

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
#include <algorithm>
#include <cstring>
#include <string>
using std::string;

class Solution {
public:
bool isPalindrome(string s) {
int i;
int n = s.size();
string original;

for (i = 0; i < n; i++) {
if (s[i] >= 'A' && s[i] <= 'Z')
s[i] = s[i] - ('A' - 'a');

if (!(s[i] >= 'a' && s[i] <= 'z') && !(s[i] >= '0' && s[i] <= '9'))
s[i] = '*';
}

s.erase(std::remove(s.begin(), s.end(), '*'), s.end());

original = s;
std::reverse(s.begin(), s.end());

if (std::strcmp(s.c_str(), original.c_str()) == 0)
return true;
else
return false;

}
};