” A palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction “
Palindrome, Wikipedia
A popular problem is how to determine if a String is a Palindrome or not, the following will also assume we are only dealing with Palindromes of single words ie. no spaces or punctuation.
The way to determine this is to compare the characters on the left and right ends of the String. If they don’t match then its not a Palindrome. If they match then we need to compare the next two most inner characters. We continue this until we find a pair that don’t match or we reach the ‘middle’ of the String. If we reach the middle then we have a Palindrome.
This can be done using either a loop or recursion. The following code shows how it can be achieved using a loop.
public class Palindrome { public static void main(String[] args) { String[] input = { "abcdefg", "abccba", "abcba", "hannah", "array", "java" }; // Loop through an array of Strings, // testing if each is a Palindrome or not for (int i=0; i<input.length; i++) { // Test if next string is a palindrome boolean palindrome = isPalindrome(input[i]); if (palindrome) { System.out.println(input[i]+" is a palindrome"); } else { System.out.println(input[i]+" is not a palindrome"); } } } /** * Test whether a given String is a Palindrome or not * @param s the String to test * @return true is String is a palindrome, false otherwise */ public static boolean isPalindrome(String s) { // Start two indexes // One from left side of string int left = 0; // And the other from right side int right = s.length() - 1; // Now compare characters from the outside in //. Once we get to the middle we can stop while (left<right) { // Compare characters if (s.charAt(left)!=s.charAt(right)) { // They are different so its not a palindrome return false; } // test the next characters in left++; right--; } // All the characters matched so it must be a palindrome return true; } }
We’ll cover a recursive solution to the same problem in a future post.
Thanks so much for this, I had looked at so many Palindrome examples that I couldn’t understand. Finally got it after studying this example.
Thanks again, will definitely visit your site again.