Friday, March 8, 2013

[LeetCode] Valid Palindrome

Thought:
Skip the special characters.

Code:
public class Solution {
    public boolean isPalindrome(String s) {
        char[] char_set = s.toCharArray();
        if (s.length() == 0) return true;
       
        int first = 0;
        int last = char_set.length - 1;
       
        while (first < last) {
            while ( !Character.isLetterOrDigit(char_set[first]) ) {
                first++;
                if (first == char_set.length - 1) return true;
            }   
            while ( !Character.isLetterOrDigit(char_set[last]) ) {
                last--;
            }
            char tmp1 = Character.toLowerCase(char_set[first]);
            char tmp2 = Character.toLowerCase(char_set[last]);
           
            if( ! (tmp1 == tmp2) ) return false;
            first++;
            last--;
        }
        return true;
    }
}

No comments:

Post a Comment