Skip to content

Instantly share code, notes, and snippets.

@samterrell
Forked from gnarl/ReverseString.java
Created April 24, 2012 00:33
Show Gist options
  • Save samterrell/2474945 to your computer and use it in GitHub Desktop.
Save samterrell/2474945 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;
}
}
@samterrell
Copy link
Author

If you return reverseAry(*) instead of assigning, you get tail recursion, which saves stack space. Also, for some reason, String.valueOf() is magically faster than new String() in many benchmarks. I have never done the research to figure out what the constructor does differently.

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