Valid Palindrome

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.

去掉全部符号然后前后比较即可。 注意character包含字母和数字。

 1 public class Solution {
 2     public boolean isPalindrome(String s) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         s = s.toLowerCase();
 6         StringBuffer ss = new StringBuffer();
 7         for(int i = 0; i < s.length(); i ++){
 8             if((s.charAt(i) - 'a' > -1 && s.charAt(i) - 'z' < 1) || (s.charAt(i) - '0' > -1 && s.charAt(i) - '9' < 1)){
 9                 ss.append(s.charAt(i));
10             }
11         }
12         for(int i = 0; i < ss.length() / 2; i ++){
13             if(ss.charAt(i) != ss.charAt(ss.length() - 1 - i))return false;
14         }
15         return true;
16     }
17 }

 不使用额外的空间:

 1 public class Solution {
 2     public boolean isPalindrome(String s) {
 3         if(s == null) return true;
 4         s = s.toLowerCase();
 5         int i = 0, j = s.length() - 1;
 6         while(i < j){
 7             while(i < j && !(s.charAt(i) >= 'a' && s.charAt(i) <= 'z') && !(s.charAt(i) >= '0' && s.charAt(i) <= '9')) i ++;
 8             while(i < j && !(s.charAt(j) >= 'a' && s.charAt(j) <= 'z') && !(s.charAt(j) >= '0' && s.charAt(j) <= '9')) j --;
 9             if(s.charAt(i) != s.charAt(j))return false;
10             else{i ++; j --;}
11         }
12         return true;
13     }
14 }

 

posted on 2013-09-11 07:36  Step-BY-Step  阅读(170)  评论(0编辑  收藏  举报

导航