Open In App

Java Program to Reverse a Sentence Using Recursion

Last Updated : 11 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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. 

Example:

Input : GeeksforGeeks
Output:    skeegrofskeeG

Input : Alice
Output: ecilA

Approach:

  1. Check if the string is empty or not, return null if String is empty.
  2. If the string is empty then return the null string.
  3. 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:

Java




// Java Program to Reverse a Sentence Using Recursion
import java.io.*;
 
public class GFG {
    public static String reverse_sentence(String str)
    {
        // check if str is empty
        if (str.isEmpty())
            // return the string
            return str;
        else {
           
            // extract the character at 0th index, that is
            // the character at beginning
            char ch = str.charAt(0);
           
            // append character extracted at the end
            // and pass the remaining string to the function
            return reverse_sentence(str.substring(1)) + ch;
        }
    }
 
    public static void main(String[] args)
    {
        // specify the string to reverse
        String str = "Geeksforgeeks";
       
        // call the method to reverse sentence
        String rev_str = reverse_sentence(str);
       
        // print the reversed sentence
        System.out.println(
            "Sentence in reversed form is :  " + rev_str);
 
        // creating another string with numbers
        // and special characters
        String str2 = "Alice";
       
        String rev_str2 = reverse_sentence(str2);
       
        // print the reversed sentence
        System.out.println(
            "Sentence in reversed form is :  " + rev_str2);
    }
}


Output

Sentence in reversed form is :  skeegrofskeeG
Sentence in reversed form is :  ecilA

Time Complexity: O(N), where N is the length of the string.

Auxiliary Space: O(N) for call stack



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads