Leetcode–Valid Palindrome

The Problem:

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.

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. Ignore cases: convert all to lowercase
  2. Only alphanumeric: first I wrote a function to check each char if is alphanumeric. Then another way to handle it is to use regular expression replace all non-alphanumeric char with “”

Java Solution

public class Solution {
    public boolean isPalindrome(String s) {
        s = s.toLowerCase();
        s = s.replaceAll("[^A-Za-z0-9]", "");
        if(s.length()== 0)return true;
        for(int i = 0, j = s.length()-1; i<=j; i++, j-- ){
            if(s.charAt(i) != s.charAt(j))
                return false;
        return true;

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