Photo by Arnold Francisca on Unsplash
Solving the Palindrome Checker Problem: From Basic to Optimized Solutions
Introduction
Palindromes are fascinating! Whether it's a word, phrase, or number, a palindrome reads the same backward as forward. In this blog post, we'll tackle the Palindrome Checker problem, starting with a basic solution and refining it to meet professional standards. By the end, you'll have a clear understanding of how to solve this problem efficiently and handle edge cases like a pro.
Problem Statement
Write a function that checks if a given word or phrase is a palindrome. A palindrome is a string that reads the same backward as forward, ignoring spaces, punctuation, and case.
Examples
"racecar"
→true
"A man, a plan, a canal, Panama"
→true
"hello world"
→false
"12321"
→true
"No lemon, no melon"
→true
Constraints
The input can contain:
Uppercase and lowercase letters.
Spaces and punctuation.
Numbers.
The solution should be case-insensitive.
Spaces and non-alphanumeric characters should be ignored.
The function should handle edge cases, such as empty strings or strings with only spaces.
Initial Logic
To solve this problem, I broke it down into the following steps:
Normalize the Input:
Convert the string to lowercase to make the check case-insensitive.
Remove spaces and non-alphanumeric characters.
Reverse the String:
- Create a reversed version of the normalized string.
Compare the Strings:
- If the normalized string and its reversed version are the same, it's a palindrome.
Initial Code
Here’s the first version of the code I wrote:
import java.util.Scanner;
public class PalindromeChecker {
public static void checker() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter word or phrase: ");
String mytext = scanner.nextLine();
// Normalize the input: lowercase and remove spaces
String palindrome = mytext.toLowerCase().replace(" ", "");
String reversedPalindrome = "";
// Reverse the string
for (int i = palindrome.length() - 1; i >= 0; i--) {
reversedPalindrome += palindrome.charAt(i);
}
// Check if it's a palindrome
if (reversedPalindrome.equals(palindrome)) {
System.out.println("The word/phrase \"" + mytext + "\" is a palindrome.");
} else {
System.out.println("The word/phrase \"" + mytext + "\" is not a palindrome.");
}
scanner.close();
}
}
Explanation of the Initial Code
Input Handling:
- The program reads the user’s input using
Scanner
.
- The program reads the user’s input using
Normalization:
- The input is converted to lowercase and spaces are removed using
toLowerCase()
andreplace(" ", "")
.
- The input is converted to lowercase and spaces are removed using
Reversing the String:
- A
for
loop iterates through the string in reverse order and builds the reversed string using+=
.
- A
Palindrome Check:
- The program compares the normalized string with its reversed version using
equals()
.
- The program compares the normalized string with its reversed version using
Limitations of the Initial Code
While the initial solution works for basic cases, it has some limitations:
Inefficient String Concatenation:
- Using
+=
to build the reversed string is inefficient because strings are immutable in Java, and each concatenation creates a new object.
- Using
No Edge Case Handling:
- The code does not handle empty strings, strings with only spaces, or non-alphanumeric characters.
Hardcoded Input:
- The program relies on
Scanner
for input, making it less reusable.
- The program relies on
Improved Version
Here’s the improved version of the code, addressing the limitations:
public class palindromeChecker {
public static boolean checker( String inputString ) {
if (inputString == null || inputString.trim().isEmpty()) {
return false;
}
String palindrome = inputString.toLowerCase().replaceAll("[^a-z0-9]", "");
// Reverse the string using StringBuilder
StringBuilder reversedPalindrome = new StringBuilder(palindrome).reverse();
// Compare the normalized input with its reversed version
return palindrome.equals(reversedPalindrome.toString());
}
}
Why the Improved Version is Better
Efficient String Reversal:
- Uses
StringBuilder.reverse()
for efficient string reversal, avoiding the inefficiency of+=
.
- Uses
Edge Case Handling:
Handles null, empty strings, and strings with only spaces.
Removes non-alphanumeric characters using
replaceAll("[^a-z0-9]", "")
.
Reusable Method:
- The
isPalindrome
method takes a string as input and returns a boolean, making it reusable and testable.
- The
Conclusion
Solving the Palindrome Checker problem taught me the importance of writing efficient, reusable, and robust code. By refining my initial solution, I learned how to handle edge cases, optimize performance, and write clean, professional code. Whether you're preparing for an interview or just sharpening your coding skills, this problem is a great way to practice!