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 a palindrome.
Note:
Are you consider that the string might is empty? This was a good question to ask during a interview.
For the purpose of this problem, we define empty string as valid palindrome.
is mainly the boundary of the judgment, empty string is considered a palindrome string
Non-recursive program
Class Solution {
Public
void Toa (String &s)
{
for (int i=0;i<s.size (); i++)
{
if (s[i]>= ' A ' &&s[i]<= ' Z ')
s[i]=s[i]+32;
}
}
BOOL Isalpha (char ch)
{
if ((ch>= ' a ' && ch<= ' z ') | | (ch>= ' 0 ' &&ch<= ' 9 '))
return true;
Else
return false;
}
BOOL Ispalindrome (string s) {
if (S.size () <=1)
return true;
int begin=0;
int End=s.size ()-1;
Toa (s);
while (Begin<=end)
{
if (! ( Isalpha (S[begin]))
begin++;
else if ((!isalpha (s[end)))
end--;
else if (S[begin]==s[end])
{
begin++;
end--;
}
Else
{
return false;
}
}
return true;
}
};
Recursive algorithm
Class Solution {
Public
void Toa (String &s)
{
for (int i=0;i<s.size (); i++)
{
if (s[i]>= ' A ' &&s[i]<= ' Z ')
s[i]=s[i]+32;
}
}
BOOL Isalpha (char ch)
{
if ((ch>= ' a ' && ch<= ' z ') | | (ch>= ' 0 ' &&ch<= ' 9 '))
return true;
Else
return false;
}
BOOL Ispalindrome (string s) {
if (S.size () <=1)
return true;
int begin=0;
int End=s.size ()-1;
Toa (s);
if (! ( Isalpha (S[begin]))
Return Ispalindrome (S.substr (begin+1,end));
else if ((!isalpha (s[end)))
Return Ispalindrome (S.substr (begin,end-1));
else if (S[begin]==s[end])
{
Return Ispalindrome (S.substr (begin+1,end-1));
}
Else
{
return false;
}
}
};
The test case "AB" on the web is unsuccessful, but in VS you can
The judgement of the palindrome string with punctuation