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) {
if(s.empty())
return true;
int i = 0, j = s.size() - 1;
while(j > i)
{
while(!isNumChar(s[i]) && i < s.size())
i++;
while(!isNumChar(s[j]) && j > 0)
j--;
if(i > j)
break;
if(toUpper(s[i]) != toUpper(s[j]))
return false;
i++;
j--;
}
return true;
}
private:
bool isNumChar(char input)
{
if((input >= 'a' && input <= 'z') || (input >= 'A' && input <= 'Z') || (input >= '0' && input <= '9'))
return true;
return false;
}
char toUpper(char input)
{
if(input >= 'a' && input <= 'z')
return input - 0x20;
else
return input;
}
};
Round2:
class Solution {
public:
bool isPalindrome(string s) {
int left = 0, right = s.size()-1;
while(left < right)
{
if(helper(s[left]) == false)
{
left++;
continue;
}
else if(helper(s[right]) == false)
{
right--;
continue;
}
else
{
if(toLower(s[left]) == toLower(s[right]))
{
left++;
right--;
}
else
{
return false;
}
}
}
return true;
}
bool helper(char c)
{
if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
return true;
else
return false;
}
char toLower(char c)
{
if(c >= 'A' && c <= 'Z')
{
return c + 32;
}
else
return c;
}
};
Round 3:
class Solution {
public:
bool isPalindrome(string s) {
if(s.empty())
return true;
int l = 0, r = s.size()-1;
while(l < r)
{
if(!isAlphaNum(s[l]))
{
l++;
continue;
}
if(!isAlphaNum(s[r]))
{
r--;
continue;
}
if(toupper(s[l]) != toupper(s[r]))
{
return false;
}
l++;
r--;
}
return true;
}
private:
bool isAlphaNum(char c)
{
if((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))
return true;
else
return false;
}
};