Hi,
I have been tasked to a string recursive problem for my computer science homework. The task is to write a recursive method with the following signature: public String mirror(String str) that returns a copy of the string, followed by all the letters except the last in reverse order. For example, if given "Saturday", you should return "SaturdayadrutaS".
I have written a java code that does the mirror but I seem to get the complete string together. Hope someone can give me some hints on how to achieve the result using recursion.
This is the code:
public String mirror(String str){
int length = str.length();
Not if the recursive method has to have the signature shown.
You can do it if your mirror method can call a method with a different signature which is recursive but why would you even want to do this with recursion? There are much better and much easier ways of achieving the required result.
Not if the recursive method has to have the signature shown.
You can do it if your mirror method can call a method with a different signature which is recursive but why would you even want to do this with recursion? There are much better and much easier ways of achieving the required result.
I think it is possible (and quite easy) with a method with that signature. But I agree with you that there are better solutions without using recursion.
@raylistic87, your attempt is not too far from a recursive solution, but you are only getting the string reversed. Just remember that each character in the original string (except for the last one) goes twice in the result.
Have a look at the example you were given:
Code:
Saturday => SaturdayadrutaS
Thinking "recursively", you take the first character (S) and you return that character followed by the mirror of the rest of the string (aturday) followed by the first character again. If the string has only one character just return it (you are doing this already).
Thinking "recursively", you take the first character (S) and you return that character followed by the mirror of the rest of the string (aturday) followed by the first character again. If the string has only one character just return it (you are doing this already).
I think it is possible (and quite easy) with a method with that signature. But I agree with you that there are better solutions without using recursion.
@raylistic87, your attempt is not too far from a recursive solution, but you are only getting the string reversed. Just remember that each character in the original string (except for the last one) goes twice in the result.
Have a look at the example you were given:
Code:
Saturday => SaturdayadrutaS
Thinking "recursively", you take the first character (S) and you return that character followed by the mirror of the rest of the string (aturday) followed by the first character again. If the string has only one character just return it (you are doing this already).
Bookmarks