Arrays & Hashing

Palindrome checker

Estimated reading: 2 minutes 46 views

Task:

  • Write a function that determines whether a given string is a palindrome.

Rules:

  • A palindrome is a word, phrase, number, or other sequence of characters that reads the same backward as forward.
  • Ignore case sensitivity (e.g., “Racecar” is considered a palindrome).
  • Remove non-alphanumeric characters before checking (e.g., “A man, a plan, a canal, Panama!” is a palindrome).

Example:

  • Input: “TAS AT”

  • Output: true

  • Input: “1234 a 4323”

  • Output: false

  • Input: “Arazi küçük. İz ara”

  • Output: true

				
					public class PalindromeChecker {

    public static boolean isPalindrome(String input) {
        // Normalize the string: convert to lowercase and remove non-alphanumeric characters
        StringBuilder normalized = new StringBuilder();
        
        for (char ch : input.toCharArray()) {
            // Check if the character is alphanumeric
            if (Character.isLetterOrDigit(ch)) {
                normalized.append(Character.toLowerCase(ch));
            }
        }

        // Compare the normalized string with its reverse without using built-in reverse
        int left = 0;
        int right = normalized.length() - 1;

        while (left < right) {
            if (normalized.charAt(left) != normalized.charAt(right)) {
                return false; // Not a palindrome
            }
            left++;
            right--;
        }

        return true; // Is a palindrome
    }

    public static void main(String[] args) {
        // Test cases
        System.out.println(isPalindrome("TAS AT")); // Output: true
        System.out.println(isPalindrome("1234 a 4323")); // Output: false
        System.out.println(isPalindrome("Arazi küçük. İz ara")); // Output: true
        System.out.println(isPalindrome("A man, a plan, a canal, Panama!")); // Output: true
    }
}

				
			
				
					import java.util.regex.Pattern;

public class PalindromeChecker {

    public static boolean isPalindrome(String str) {
        // Convert to lowercase and remove non-alphanumeric characters
        String cleanedStr = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", "");

        // Check if the cleaned string is equal to its reverse
        return cleanedStr.equals(new StringBuilder(cleanedStr).reverse().toString());
    }

    public static void main(String[] args) {
        String str1 = "TAS AT";
        String str2 = "1234 a 4323";
        String str3 = "Arazi küçük. İz ara";

        System.out.println(isPalindrome(str1)); // Output: true
        System.out.println(isPalindrome(str2)); // Output: false
        System.out.println(isPalindrome(str3)); // Output: true
    }
}
				
			
Share this Doc

Palindrome checker

Or copy link

CONTENTS