[leetcode]_Valid Palindrome

题目:判断一个数字字符串是否是回文串。空串认为是回文串。

思路:双指针问题,重点在于此题的很多陷进:例如,s = " " ,return true。 s = ".," , return true。

代码:修改了很多遍,终于AC , 要点在于只有当头尾两个指针都指向数字或者字母时,此时才有比较操作,否则都认为是相等的。 

 1 public boolean isPalindrome(String s) {
 2         
 3         int i = 0 , j = s.length() - 1;
 4         char left = 0 , right = 0 ;
 5         while( i <= j ){ // 控制循环结束,所有元素都已经遍历过了。
 6     
 7             left = s.charAt(i);
 8             if(!ifLegal(left)){
 9                 i++;    
10                 continue;
11             }  
12           
13             right = s.charAt(j);
14             if(!ifLegal(right)) {
15                 j--;
16                 continue;
17             }
18             
19             //只有当left 和 right 同时指向数字、字母时,才进行比较;其它情况都认为是相等的。
20             if((left != right && Math.abs(left - right) != ('a' - 'A'))) return false;
21             i++;
22             j--;
23         }
24         return true;       
25     }
26     
27     public boolean ifLegal(char ch){
28         if(ch >= 'a' && ch <= 'z') return true;
29         if(ch >= 'A' && ch <= 'Z') return true;
30         if(ch >= '0' && ch <= '9') return true;
31         
32         return false;
33     }
原文地址:https://www.cnblogs.com/glamourousGirl/p/3753431.html