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.
题目:判断字串是否是回文字串
思路:两个指针分别从字串的头部与尾部向中间走,只有遇到是字符才比较是否相等,任何一个指针遇到其他符号都继续走,直到是字符或者已到字符边界为止为止。
注意:
1、空字符也是回文
2、一定要边界判断,否则当字符串中只有特殊符号没有字母的时候就会越界,在VS2012中居然越界程序没有崩溃,LINUX中也没有。
3、不区分大小写
4、当strlen(s) < 2 一定是回文
#include
#include
#include
#include
#include
#define isstr(a) ((a>='a'&&a<='z')||(a>='A'&&a<='Z')||(a>='0'&&a<='9')) bool isPalindrome(char* s) { if(NULL == s) return true; if('' == s) return true; if(strlen(s) < 2) return true; char* pa = s; char* pb = s; char* l = s;//border of pa point while(*pb != '') pb++; pb--; //make pb point the last character,nor ''!! char* n = pb;//border of pb point while(pa < pb) { while(!isstr(*pa) && pa<=n) pa++; while(!isstr(*pb) && pb>=l) pb--; if(((*pa != *pb) && (abs(*pa-*pb) != 'a'-'A')) && (isstr(*pa)) && (isstr(*pb))) return false; else { pa++; pb--; } } return true; } int main() { char* s = A man, a plan, a canal: panama; bool r = isPalindrome(s); printf(s is isPalindrome? : %d ,r); char *s1 = ; bool r1 = isPalindrome(s1); printf(s1 is isPalindrome? : %d ,r1); char *s2 = *.; bool r2 = isPalindrome(s2); printf(s2 is isPalindrome? : %d ,r2); char *s3 = Sore was I ere I saw Eros.; bool r3 = isPalindrome(s3); printf(s3 is isPalindrome? : %d ,r3); }
?