Formatted question description:

125	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.

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.



Only need to establish two pointers, left and right, to traverse the entire string from the beginning and the end of the character respectively.

  • If a non-alphanumeric character is encountered, it will be skipped and the search will continue until the next alphanumeric or end is found.
  • or continue to traverse, if it encounters an uppercase letter, convert it to lowercase. When both the left and right pointers find alphanumeric characters, compare these two characters,
    • if they are equal, continue to compare the following two alphanumerics found separately,
    • if not equal, return false


  1. Replace() and replaceAll() did not add All at the beginning, if it is not replaceAll(), it is pure char matching, and has nothing to do with regex Therefore, you must replaceAll() to match regex

  2. Regex: ^ should be placed inside the parentheses, not outside the parentheses, otherwise ^ will not work, and then delete everything you want to leave

         [abc]	Find any character between the brackets
         [^abc]	Find any character NOT between the brackets
         [0-9]	Find any digit between the brackets
         [^0-9]	Find any digit NOT between the brackets
         (x|y)	Find any of the alternatives specified



public class Valid_Palindrome {

	public class Solution {
	    public boolean isPalindrome(String s) {
	                if (s.length() == 0) {
	            return true;

	        // regex to keep only chars
	        s = s.replaceAll("[^a-zA-Z0-9]", ""); // replace non-characters with empty, i.e. remove them

	        s = s.toLowerCase();

	        int i = 0;
	        int j = s.length() - 1;
	        while (i <= j) {
	            if (s.charAt(i) != s.charAt(j)) {
	                return false;


	        return true;



All Problems

All Solutions