-
-
Save samterrell/2474945 to your computer and use it in GitHub Desktop.
Recursive String Reverse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.