Valid Palindrome - Java Solution

1. Introduction

In this post, we explore the intriguing problem of determining whether a string is a palindrome. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward, disregarding spaces, punctuation, and capitalization. This challenge not only tests our understanding of strings in Java but also our ability to manipulate and process data efficiently.

Problem

We need to check if a given string is a palindrome. This involves converting all uppercase letters to lowercase and removing all non-alphanumeric characters. After these transformations, if the string reads the same forwards and backward, it is a palindrome.

2. Solution Steps

1. Convert the string to lowercase to ensure case-insensitivity.

2. Remove all non-alphanumeric characters.

3. Check if the cleaned string is a palindrome.

3. Code Program

public class ValidPalindrome {
    public static void main(String[] args) {
        System.out.println(isPalindrome("A man, a plan, a canal: Panama")); // Example 1
        System.out.println(isPalindrome("race a car"));                    // Example 2
        System.out.println(isPalindrome(" "));                             // Example 3
    }

    // Function to check if a string is a palindrome
    public static boolean isPalindrome(String s) {
        String cleaned = s.toLowerCase().replaceAll("[^a-z0-9]", ""); // Step 1 & 2: Clean the string
        return isPalindromeCleaned(cleaned);
    }

    // Helper function to check palindrome on cleaned string
    private static boolean isPalindromeCleaned(String str) {
        int left = 0, right = str.length() - 1;
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false; // If characters do not match
            }
            left++; // Move left index towards the center
            right--; // Move right index towards the center
        }
        return true; // String is a palindrome
    }
}

Output:

true
false
true

Explanation:

1. isPalindrome: This function starts by cleaning the input string - converting it to lowercase and removing non-alphanumeric characters.

2. isPalindromeCleaned: It then checks if the cleaned string is a palindrome by using two pointers, one starting from the beginning and the other from the end of the string. If the characters at these pointers don't match at any point, the function returns false. If the pointers meet or cross without any mismatch, it's confirmed that the string is a palindrome.


Comments