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:
- 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:
Java
import java.io.*;
public class GFG {
public static String reverse_sentence(String str)
{
if (str.isEmpty())
return str;
else {
char ch = str.charAt( 0 );
return reverse_sentence(str.substring( 1 )) + ch;
}
}
public static void main(String[] args)
{
String str = "Geeksforgeeks" ;
String rev_str = reverse_sentence(str);
System.out.println(
"Sentence in reversed form is : " + rev_str);
String str2 = "Alice" ;
String rev_str2 = reverse_sentence(str2);
System.out.println(
"Sentence in reversed form is : " + rev_str2);
}
}
|
OutputSentence 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