valid Palindrome

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.

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.

Solution

Two Pointer Solution: O(n) time

public class Solution {
    public boolean isPalindrome(String s) {
        if (s == null || s.length() < 2) return true;
        String str = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); //Make checking easier below 
        int start = 0, end = str.length() - 1;
        while (start < end) {
            if (str.charAt(start++) != str.charAt(end--)) return false;
        }
        return true;
    }
}

Analysis

We use regex "[^a-zA-Z0-9]" to replace all other patterns into ""
Then we call toUpperCase() to ignore the case difference
Simply check in a while loop using two pointers and return the result

results matching ""

    No results matching ""