-
-
Save Morse-Code/2475973 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
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)