The judgement of the palindrome string with punctuation

Source: Internet
Author: User
Tags alphanumeric characters

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.