January 26, 2024

Java Problems Solutions: Check if a String is a Palindrome


public class CheckPalindrome {
    public static void main(String[] args) {
    	String inputString = "Was it a car or a cat I saw?";
        // Check if the input string is a palindrome.
        if (isPalindrome(inputString)) {
            System.out.println("The given string is a palindrome.");
        } else {
            System.out.println("The given string is not a palindrome.");
        }
    }
    // Function to check if a string is a palindrome
    public static boolean isPalindrome(String str) {
        // Remove spaces and convert to lower case for case-insensitive comparison.
    	str = str.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
        int left = 0;
        int right = str.length() - 1;
        // Check characters from both ends towards the center
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false; // Characters do not match, so its not a palindrome.
            }
            left++;
            right--;
        }
        return true; // All characters matched, so its a palindrome.
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please.


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.