This code works for testing a simple palindrome, but I'm confused as to how it works.
I'm confused with the while loop condition, checking if (left < right)
and how that automatically means it is not a palindrome.
left = 0;
right = i.length() -1;
while(i.charAt(left) == i.charAt(right) && right > left){
left++;
right--;
}
System.out.println();
if (left < right)
System.out.println ("That string is Not a palindrome.");
else
System.out.println("That string IS a palindrome");
It helps to use print statements to watch what the program is doing as it runs.
class Ideone
{
private static void checkPalindrome(String i) {
int left = 0;
int right = i.length() -1;
System.out.println("This word is: " + i);
System.out.println("Checking charAt(" + left + ") which is " +
i.charAt(left) + " and chartAt(" + right + ") which is " +
i.charAt(right));
while(i.charAt(left) == i.charAt(right) && right > left) {
left++; right--;
System.out.println("Checking charAt(" + left + ") which is " +
i.charAt(left) + " and chartAt(" + right + ") which is " +
i.charAt(right));
}
System.out.println();
if (left < right)
System.out.println ("That string is Not a palindrome.");
else
System.out.println("That string IS a palindrome");
System.out.println();
}
public static void main (String[] args) throws java.lang.Exception
{
checkPalindrome("racecar");
checkPalindrome("abba");
checkPalindrome("java");
}
}
This word is: racecar
Checking charAt(0) which is r and chartAt(6) which is r
Checking charAt(1) which is a and chartAt(5) which is a
Checking charAt(2) which is c and chartAt(4) which is c
Checking charAt(3) which is e and chartAt(3) which is e
That string IS a palindrome
This word is: abba
Checking charAt(0) which is a and chartAt(3) which is a
Checking charAt(1) which is b and chartAt(2) which is b
Checking charAt(2) which is b and chartAt(1) which is b
That string IS a palindrome
This word is: java
Checking charAt(0) which is j and chartAt(3) which is a
That string is Not a palindrome.
As you can see, the while loop starts from the far ends of the string and compares the characters on each side; if they are the same, it moves in one character on each side. It checks for right > left
so that it knows when to stop. Once it reaches the middle, right
will be at least equal, if not greater than, left
since they have met in the middle and are going opposite directions.
The boolean negation of left < right
is equivalent to left >= right
. This'll be true if the two met in the middle. If left < right
then they failed to meet in the middle. You should be able to see this in the above output.
Run this code on ideone and play with it some more.