In this tutorial, you will learn how to check if a string is a palindrome in Java using recursion. A String is nothing but collection of characters e.g. "Java" and String literals are encoded in double quotes in Java. A String is said to be palindrome if reverse of String is equal to itself e.g. "aba" is a palindrome because reverse of "aba" is also "aba", but "abc" is not a palindrome because reverse of "abc" is "cba" which is not equal. Recursion means solving a problem by writing a function which calls itself. In order to check if String is palindrome in Java, we need a function which can reverse the String. Once you have original and reversed String, all you need to do is check if they are equal to each other or not. If they are equal then String is palindrome or not. You can write this reverse() function by using either for loop or by using recursion. If you remember, I already shared logic of reversing String in my earlier post, how to reverse String in Java using Iteration and recursion. Here we will use the same logic to check if String is palindrome or not. By the way, if you are preparing for coding interviews and looking for some coding problem to get hands on practice, I suggest you to take a look at Cracking the Coding Interview: 150 Programming Questions and Solutions. This is a wonderful book, which contains lots of easy and medium difficulty level coding problems, which will not only help you to prepare for interview but also develop your programming logic.
Read more »
No comments:
Post a Comment