题目:
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.
思路:从两头开始往中间靠拢,需要进行比对。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
/*
判断一个字符串是否为回文字符串 这里只比较字符,大写字符和小写字符
看成是一样的
*/
bool helper(string& str,int begin,int end)
{
if(begin == end)
return true;
if(begin > end)
return false;
if(isalpha(str[begin]) && isalpha(str[end]))
{
if(toupper(str[begin]) == toupper(str[end]))
return helper(str,begin+1,end-1);
else
return false;
}
else if(!isalpha(str[begin]) && isalpha(str[end]))
return helper(str,begin+1,end);
else if(isalpha(str[begin]) && !isalpha(str[end]))
return helper(str,begin,end-1);
else
return helper(str,begin+1,end-1);
}
bool isVaildPalindrome(string& str)
{
if(str.length()==0)
return 0;
return helper(str,0,str.length()-1);
}
int main()
{
string str("A man, a plan, a canal: Panama");
cout<<isVaildPalindrome(str);
return 0;
}