Wednesday, July 3, 2013

Checking for Palindromes in Java

In our first year at KCL, I remember a lab assignment to write something which would check for palindromes. So when recently I came through this question apparently posed during a Facebook interview to check for palindromes whilst ignoring spaces, I felt this shouldn't be mind bogging.

It certainly isn't. In my code below, I have created an internal private class Cursor, which as its name suggests will act as a cursor on the String. The cursor can move one character at a time, either backwards or forwards.  Two cursor objects will be initialised, head and tail. The head will move from the first character whereas the tail will move from the last. This will be so until they reach opposite ends and the head is at a position lower than the tail.

To avoid spaces, I loop the head cursor, until it finds a valid character. I follow this by looping the tail cursor until it finds a valid character as well. And then finally compare them, if they dont match then the test is terminated with the method returning false.

No comments:

Post a Comment