Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama"
is a palindrome.
"race a car"
is not a palindrome.
Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome
class Solution {
public:
bool isPalindrome(string s) {
for (int l=plus(-1,s), r = minus(s.size(),s); l<r; l=plus(l,s), r=minus(r,s)) {
if (!isequal(s[l],s[r])) {
return false;
}
}
return true;
}
bool isAlpha(const char c) {
return (c >='a' && c <= 'z') || (c >= 'A' && c<= 'Z') || (c >= '0' && c <= '9');
}
bool isequal(const char c1, const char c2) {
if (c1 == c2) {
return true;
} else if (c1 > c2) {
return (c1 -'a') == (c2 -'A');
} else {
return (c2 -'a') == (c1 -'A');
}
}
int plus(int left, const string &s) {
while (left < int(s.size())) {
left++;
if (isAlpha(s[left])) {
break;
}
}
return left;
}
int minus(int right, const string &s) {
while (right >= 0) {
right--;
if (isAlpha(s[right])) {
break;
}
}
return right;
}
};
2nd iteration
class Solution {
public:
bool isPalindrome(string s) {
// put them to lower case to deal with case-insensitive
transform(s.begin(), s.end(), s.begin(), ::tolower);
int i = 0, j = s.size()-1;
// two pointer from head and tail
while (i < j) {
// ignore non alpha-numeric characters
// stop at first alpha-numeric character or up bound j
while (i < j && !isAlphaNumeric(s[i])) {
i++;
}
// ignore non alpha-numeric characters
// stop at first alpha-numeric character
while (i < j && !isAlphaNumeric(s[j])) {
j--;
}
// either two alpha-numeric characters
// or i == j for non-alpha-numeric character,
// which will be equal==> reault in i < j and return true, see blow
if (s[i] != s[j]) {
break;
}
i++;
j--;
}
// two alpha-numeric character not equal
if (i < j) {
return false;
} else {
// one alpha-numeric character
// non-alpha-numeric characters
// all alpha-numeric characters are equal
return true;
}
}
bool isAlphaNumeric(const char c) {
return isalpha(c) || isdigit(c);
}
};