这道题挺简单的,但是需要细心。
最好的方法是先对string做预处理,然后再判断是否是回文。
下面是AC代码:
1 /** 2 * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. 3 * @param s 4 * @return 5 */ 6 public boolean isPalindrome(String s){ 7 String pre = preProcess(s); 8 char[] sw = pre.toCharArray(); 9 if(pre==null || pre.length()<=1 )10 return true;11 int i=0;12 int j=pre.length()-1;13 while(i<=j){14 if(sw[i]!=sw[j])15 return false;16 i++;17 j--;18 }19 return true;20 }21 /**22 * pre-processing the string, remove all non-isAlphanumeric23 * and change all to lower24 * @param s25 * @return26 */27 private String preProcess(String s){28 29 StringBuffer sb = new StringBuffer();30 for(int i=0;i='a' && c<='z' || c>='A' && c<='Z' || c>='0'&& c<='9')42 return true;43 return false;44 }