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.

 

public boolean isPalindrome(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(s==null || s.length()<=1){
            return true;
        }
        String lowercase = s.toLowerCase();
        ArrayList<Character> validChars = new ArrayList<Character>();
        for(int i=0;i<lowercase.length();i++){
            int asc=(int)lowercase.charAt(i);
            
            if((asc<='9' && asc>='0') ||
               (asc<='z' && asc>='a')){
                   validChars.add(lowercase.charAt(i));
               }
        }
        
        int left = 0;
        int right = validChars.size()-1;
        while(left<right){
            if(validChars.get(left)!=validChars.get(right)){
                return false;
            }else{
                left++;
                right--;
            }
        }
        return true;
    }
FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *