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.

题目大意:给一个字符串,判断它是否是回文,只考虑字母数字字符,并且忽略大小写。

分析:可用双指针解决,i指向头,j指向尾,先用tolower()函数(如果是大写字母才将其转换为小写字母,否则不变),将大写字母转换为小写字母,如果s[i]和是s[j]都是字母,判断是否相等,如果不相等,直接返回false,否则i++,j--;如果有一个不是字母,那么对应移动指针。循环条件i <= j;循环结束后还没有返回,则说明是回文,返回true;

 1 class Solution {
 2 public:
 3     bool isAlphanumericCharacters(char s){
 4         return (s >= 'a' && s <= 'z') || (s >= '0' && s <= '9');
 5     }
 6     bool isPalindrome(string s) {
 7         int len = s.length();
 8         if(len == 0)
 9             return true;
10         for(int i = 0, j = len - 1; i <= j; ){
11             char c1 = tolower(s[i]), c2 = tolower(s[j]);
12             //如果c1和c2都是字母;
13             if(isAlphanumericCharacters(c1) && isAlphanumericCharacters(c2)) {
14                 //判断是否相等
15                 if(c1 == c2){
16                     i++;
17                     j--;
18                 //不相等直接返回false;
19                 } else {
20                     return false;
21                 }
22             //如果c1是字母,c2不是字母
23             } else if (isAlphanumericCharacters(c1) && !isAlphanumericCharacters(c2)){
24                 j--;
25             //如果c1不是字母,c2是字母;
26             } else if (!isAlphanumericCharacters(c1) && isAlphanumericCharacters(c2)){
27                 i++;
28             //都不是字母
29             } else {
30                 i++;
31                 j--;
32             }
33         }
34         return true;
35     }
36 };

 

越努力,越幸运