Java Program to Reverse a Sentence Using Recursion
A sentence is a sequence of characters separated by some delimiter. This sequence of characters starts at the 0th index and the last index is at len(string)-1. By reversing the string, we interchange the characters starting at 0th index and place them from the end. The first character becomes the last, the second becomes the second last, and so on.
Input : GeeksforGeeks Output: skeegrofskeeG Input : Alice Output: ecilA
- Check if the string is empty or not, return null if String is empty.
- If the string is empty then return the null string.
- Else return the concatenation of sub-string part of the string from index 1 to string length with the first character of a string. e.g. return substring(1)+str.charAt(0); which is for string “Mayur” return will be “ayur” + “M”.
Below is the implementation of the above approach:
Sentence in reversed form is : skeegrofskeeG Sentence in reversed form is : ecilA
Time Complexity: O(N), where N is the length of the string.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.