Write a recursive function to print reverse of a given string.
Program:
C++
#include <bits/stdc++.h>
using namespace std;
void reverse(string str)
{
if(str.size() == 0)
{
return;
}
reverse(str.substr(1));
cout << str[0];
}
int main()
{
string a = "Geeks for Geeks";
reverse(a);
return 0;
}
|
C
# include <stdio.h>
void reverse(char *str)
{
if (*str)
{
reverse(str+1);
printf("%c", *str);
}
}
int main()
{
char a[] = "Geeks for Geeks";
reverse(a);
return 0;
}
|
Java
class StringReverse
{
void reverse(String str)
{
if ((str==null)||(str.length() <= 1))
System.out.println(str);
else
{
System.out.print(str.charAt(str.length()-1));
reverse(str.substring(0,str.length()-1));
}
}
public static void main(String[] args)
{
String str = "Geeks for Geeks";
StringReverse obj = new StringReverse();
obj.reverse(str);
}
}
|
Python
def reverse(string):
if len(string) == 0:
return
temp = string[0]
reverse(string[1:])
print(temp, end='')
string = "Geeks for Geeks"
reverse(string)
|
C#
using System;
class GFG
{
static void reverse(String str)
{
if ((str == null) || (str.Length <= 1))
Console.Write(str);
else
{
Console.Write(str[str.Length-1]);
reverse(str.Substring(0,(str.Length-1)));
}
}
public static void Main()
{
String str = "Geeks for Geeks";
reverse(str);
}
}
|
PHP
<?php
function reverse($str)
{
if (($str == null) ||
(strlen($str) <= 1))
echo ($str);
else
{
echo ($str[strlen($str) - 1]);
reverse(substr($str, 0,
(strlen($str) - 1)));
}
}
$str = "Geeks for Geeks";
reverse($str);
?>
|
Javascript
<script>
function reverse(str, len) {
if (len == str.length) {
return;
}
reverse(str, len + 1);
document.write(str[len]);
}
let a = "Geeks for Geeks";
reverse(a, 0);
</script>
|
Output:
skeeG rof skeeG
Explanation: Recursive function (reverse) takes string pointer (str) as input and calls itself with next location to passed pointer (str+1). Recursion continues this way when the pointer reaches ‘\0’, all functions accumulated in stack print char at passed location (str) and return one by one.
Time Complexity: O(n^2) as substr() method has a time complexity of O(k) where k is the size of the returned string. So for every recursive call, we are reducing the size of the string by one, which leads to a series like (k-1)+(k-2)+…+1 = k*(k-1)/2 = O(k^2) = O(n^2)
See Reverse a string for other methods to reverse string.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.