0%

125. Valid Palindrome

O(n) time O(1) space

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
bool isPalindrome(string s) {
for (int l = 0, r = s.length() - 1; l < r; ++l, --r) {
while (l < r && !isalnum(s[l])) ++l;
while (l < r && !isalnum(s[r])) --r;
if (tolower(s[l]) != tolower(s[r])) return false;
}
return true;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
bool isPalindrome(string s) {
int n = s.length();
int l = 0, r = n - 1;
while (l < r) {
while (l < r && !isalnum(s[l])) {
++l;
}
while (l < r && !isalnum(s[r])) {
--r;
}
if (tolower(s[l]) != tolower(s[r])) return false; // uniform case!!
++l;
--r;
}
return true;
}
};