LeetCode OJ - Valid Palindrome
这道题挺简单的,但是需要细心。
最好的方法是先对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-isAlphanumeric 23 * and change all to lower 24 * @param s 25 * @return 26 */ 27 private String preProcess(String s){ 28 29 StringBuffer sb = new StringBuffer(); 30 for(int i=0;i<s.length();i++) 31 if(isAlphanumeric(s.charAt(i))) 32 sb.append(s.charAt(i)); 33 return sb.toString().toLowerCase(); 34 } 35 /** 36 * make decision if a character is a alphanumeric 37 * @param c 38 * @return 39 */ 40 private boolean isAlphanumeric(char c){ 41 if(c>='a' && c<='z' || c>='A' && c<='Z' || c>='0'&& c<='9') 42 return true; 43 return false; 44 }
有问题可以和我联系,bettyting2010#163 dot com