leetcode -- 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.

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.

 1 public boolean isPalindrome(String s) {
 2         // Start typing your Java solution below
 3         // DO NOT write main() function
 4         int len = s.length();
 5         if(len == 0)
 6             return true;
 7             
 8         String ignoredStr = ignore(s.toLowerCase());
 9         
10         boolean result = checkPali(ignoredStr);
11         
12         return result;
13     }
14     
15     public static String ignore(String s){
16         StringBuilder sb = new StringBuilder();
17         int len = s.length();
18         for(int i = 0; i < len; i++){
19             char c = s.charAt(i);
20             if((c >= '0' && c <= '9') ||
21                 (c >= 'a' && c <= 'z')){
22                     sb.append(c);
23                 }
24         }
25         return sb.toString();
26     }
27     
28     public static boolean checkPali(String s){
29         int len = s.length();
30         boolean flag = true;
31         for(int i = 0; i < (len / 2); i++){
32             if(s.charAt(i) != s.charAt(len - 1 - i)){
33                 flag = false;
34                 return flag;
35             }
36         }
37         return flag;
38     }

 

posted @ 2013-08-07 23:25  feiling  阅读(218)  评论(0编辑  收藏  举报