Sunday, November 29, 2015

[leetcode]Valid Palindrom

上一段神code
1
2
s=s.toLowerCase().replaceAll("[^a-z0-9]", "");
return new StringBuilder(s).reverse().toString().equals(s);
简练!
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Solution {
    public boolean isPalindrome(String s) {
        int left = 0;
        int right = s.length()-1;
        while (left < right){
            char leftC = Character.toLowerCase(s.charAt(left));
            char rightC = Character.toLowerCase(s.charAt(right));
            boolean leftValid = validCheck(leftC);
            boolean rightValid = validCheck(rightC);
            if(!leftValid){
                left++;
            }
            if(!rightValid){
                right--;
            }
            if (leftValid && rightValid){
                if (leftC != rightC) return false;
                left++;
                right--;
            }
        }
        
        return true;
    }
    
    
    boolean validCheck(char a){
        return Character.isAlphabetic(a) || Character.isDigit(a);
    }
}

No comments:

Post a Comment