Skip to content

Instantly share code, notes, and snippets.

@Morse-Code
Forked from samterrell/ReverseString.java
Created April 24, 2012 03:15
Show Gist options
  • Save Morse-Code/2475973 to your computer and use it in GitHub Desktop.
Save Morse-Code/2475973 to your computer and use it in GitHub Desktop.
Recursive String Reverse
public class ReverseString {
public static void main(String[] argv) {
String origString = argv[0];
System.out.println(origString);
System.out.println(reverse(origString));
}
public static String reverse(String str) {
if(str.length()<=1) return str;
char[] strAry = str.toCharArray();
return String.valueOf(reverseAry(strAry,0,strAry.length-1,strAry[0]));
}
public static char[] reverseAry(char[] strAry, int index, int end, char c) {
strAry[index] = strAry[end];
strAry[end] = c;
return (++index<--end)?reverseAry(strAry, index, end, strAry[index]):strAry;
}
}
@arunkumardancer
Copy link

Here is the recursive equation to reverse a string using recursion
reverse(string, leftIndex, rightIndex) = swap(string, leftIndex, rightIndex) + reverse(string, leftIndex+1, rightIndex-1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment