Friday, November 7, 2014

Facebook: Write a Palindrome checking function

Write a palindrome checking function.

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.
Code (Java):
public class Solution {
    public boolean isPalindrome(String s) {
        if (s == null || s.length() < 2) {
            return true;
        // Use regx to remove non-alpha numeric characters
        String delim = "[^a-zA-Z0-9]";
        s = s.replaceAll(delim, "").toLowerCase();
        if (s.length() < 2) {
            return true;
        int lo = 0;
        int hi = s.length() - 1;
        while (lo < hi) {
            if (s.charAt(lo) == s.charAt(hi)) {
            } else {
                return false;
        return true;

No comments:

Post a Comment