Created
April 22, 2012 01:16
-
-
Save gnarl/2440662 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){ | |
char[] strAry = str.toCharArray(); | |
strAry = reverseAry(strAry, 0); | |
return new String(strAry); | |
} | |
public static char[] reverseAry(char[] strAry, int index) { | |
int oppositeIndex = strAry.length - index - 1; | |
if(oppositeIndex > index) { | |
char tmp = strAry[index]; | |
strAry[index] = strAry[oppositeIndex]; | |
strAry[oppositeIndex] = tmp; | |
strAry = reverseAry(strAry, ++index); | |
} | |
return strAry; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment