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.
分析
判斷一個字符串是否是回文串,忽略其他字符和大小寫。先將小寫字母轉化為大寫字母,之后從首尾向中間依次判斷字符和數字,不相等的話直接返回false。
bool isalphanumeric(char s)
{
if(s>='a'&&s<='z')return true;
else if(s>='A'&&s<='Z')return true;
else if(s>='0'&&s<='9')return true;
else return false;
}
bool isPalindrome(char* s) {
if(s[0]=='\0')return true;
bool flag=true;
int length=0;
while(s[length]!='\0')
{
if(s[length]>='a'&&s[length]<='z')
s[length]='A'+s[length]-'a';
length++;
}
int i=0,j=length-1;
while(i<j)
{
while(i<j&&isalphanumeric(s[i])==false)
i++;
while(i<j&&isalphanumeric(s[j])==false)
j--;
//printf("%c %c\n",s[i],s[j]);
if(i==j||(i==j-1&&s[i]==s[j]))
return true;
else if(s[i]!=s[j])
return false;
else
{
i++;j--;
}
}
return flag;
}