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.
很简单的题目: 2星级。
考点:
1 会判断是否是字母和数字
2 知道什么是Palindrome
可以利用函数库判断是否为数字或者字母,程序如下:
bool isPalindrome(string s) { for (int i = 0, j = s.size()-1; i < j; i++, j--) { while (i<j && (!isalpha(s[i]) && !isdigit(s[i]))) i++; while (i<j && (!isalpha(s[j]) && !isdigit(s[j]))) j--; if (i<j && tolower(s[i]) != tolower(s[j])) return false; } return true; }
bool isPalindrome(string s) { for (int i = 0, j = s.size()-1; i < j; i++, j--) { while (s[i] && (!isTestChar(s[i]))) i++; while (s[j] && (!isTestChar(s[j]))) j--; if (i<j && !isEqual(s[i], s[j])) return false; } return true; } bool isTestChar(char a) { int i = a; return (i>=97 && i<=122) || (i>=65 && i<=90) || (i>=48 && i<=57); } bool isEqual(char a, char b) { return a == b || int(a) == int(b)-32 || int(b) == int(a)-32; } /* char a = 'A';//65 a = 'a';//97 a = 'Z';//90 a = 'z';//122 a = '1';//49 a = '0';//48 */
//2014-2-18 update bool isPalindrome(string s) { for (int i = 0, j = s.length()-1; i < j; ) { if (isalnum(s[i]) && isalnum(s[j])) { if (tolower(s[i]) != tolower(s[j])) return false; i++, j--; } if (i<j && !isalnum(s[i])) i++; if (i<j && !isalnum(s[j])) j--; } return true; }