How to ace an interview with one line

A few years ago I had an inteview for a java job.
The interviewer posed a simple question to see if I could work stuff out.
The question was “Write a method to determine if a string was a palindrome”.
A palindrome is a word that is spelt the same froward as backward. ABBA is a famous palindrome.

I achieved it in the interview by iterating from the beging and end of the string to the middle, comparing each char, to determine if it was a palindrome.

This was the kind of answer the interviewer was looking for. Which was a shame as this shows a lack of understanding of the basic Java API. [To my credit I did say that there was bound to be a String reverse type method somewhere in the API, but that I would need to check.]

The correct answer to this rather mundane interview question is as follows;
[java]
public boolean isPalindrome(String str) {
return (new StringBuffer(str)).reverse().toString().equalsIgnoreCase(str);
}
[/java]

A single line of code. No loops. No iteration.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s