The recursive method reverseString( ) takes a single string as an argument and returns the same string with the characters in reverse order.
To do this, the method uses a base case to handle strings of length 1 or 0. Can you figure out what is the reverse string of any string that has 1 or 0 character in it ? Well, you should return this string in the base case.
Next, the method breaks the string into two parts, the first character and the rest of the string. The method recursively calls itself with the substring as an argument and then use the result to construct the reversed string. Can you figure out how to construct the reversed string using the solution of the reversed substring ? Figure this out and construct the solution and return the solution as answer !
Test the method with this main( ) program:
public class myProg
{
public static void main(String[] args)
{
System.out.println(reverseString("abcde"));
System.out.println(reverseString("uvwxyz"));
}
}
|
Your program is correct if you see:
edcba zyxwvu |