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.

Solution: replace non-alphanumeric characters by using regex.

public class Solution {
    public boolean isPalindrome(String s) {
        //eliminate all non-letter&non-numerical char 
        String regex = "([^A-Za-z0-9])";
        String replacement = "";
        s = s.replaceAll(regex, replacement); 
        for(int i =0;i<s.length()/2;i++){
            if(Character.toLowerCase(s.charAt(i))==Character.toLowerCase(s.charAt(s.length()-1-i)))
                continue;
            else 
                return false;
        }
        return true; 
    }
}

Solution 2: use Character.isLetterOrDigit().

public class Solution {
    public boolean isPalindrome(String s) {
        if (s.isEmpty()) {
            return true; 
        }
        int head = 0, tail = s.length()-1; 
        char cHead, cTail; 
        while (head < tail) {
            cHead = s.charAt(head);
            cTail = s.charAt(tail);
            if (!Character.isLetterOrDigit(cHead)) {
                head++;
            } else if (!Character.isLetterOrDigit(cTail)) {
                tail--;
            } else {
                if (Character.toLowerCase(cHead) != Character.toLowerCase(cTail)) 
                    return false;
                head++; 
                tail--;
            }
        }
        return true;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s