2

So I'm practicing java currently, I'm a beginner and I try to explain all the examples that I code so I can understand how and why things are like that. I understand the concept of recursion but I came across this problem when I tried to explain this code:

import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {
        String str;
        System.out.println("Enter your username: ");
        Scanner scanner = new Scanner(System.in);
        str = scanner.nextLine();
        scanner.close();
        String reversed = reverseString(str);
        System.out.println("The reversed string is: " + reversed);
    }

    public static String reverseString(String str)
    {
        if (str.isEmpty())
            return str;
        //Calling Function Recursively
        return reverseString(str.substring(1)) + str.charAt(0);
    }
}

With my knowledge so far about recursion, I tried to explain it like this. Let's have for example a string "Petar":

reverseString(etar)+P
reverseString((tar)+etar)+P
reverseString((ar)+tar+etar)+P
reverseString((r)+ar+tar+etar)+P
-----------------------------------
r+ar+tar+etar+P

I noticed that the right answer is the first character from every individual piece, so I must be close.

Thank you for your time and I'm sorry if I didn't express myself clearly, I'm from Europe (sry bad inglish).

5 Answers 5

1

You doing good for first line reverseString(etar)+P you keep at the end only the *first char**, just do the same for next lines

  • put first char at the end
  • send the rest to the method
reverseString(etar)+P
reverseString(tar) +e+P
reverseString(ar)  +t+e+P
reverseString(r)   +a+t+e+P
reverseString('')  +r+a+t+e+P // stops when empty string is passed
Sign up to request clarification or add additional context in comments.

1 Comment

I thought it was like: (reverseString(str.substring(1))) + str.charAt(0), aka I thought that the method was calling only for the str.substring(1). But thank for the answer it helped a lot!
1

You got the first call right but the others were a bit off. In each recursive call you return the the string with the first character at the end instead of the begining. Thus, the recursion looks something like this:

reverseString("Petar")
return reverseString("etar") + "P"
return reverseString("tar") + "e"
return reverseString("ar") + "t"
return reverseString("r") + "a"
return reverseString("") + "r"
return ""

So the function will return: (((((("")+"r")+"a")+"t")+"e")+"P"), which is "rateP".

1 Comment

Thank you very much for the explanation, I appreciate the time!
1

It should become clear when start with the simplest possible example: the empty string and string of size 1. Then substituting arguments of each call, to make it more obvious:

// string.isEmpty() is true, so the empty string is returned immediately
reverse("")  -> "" 
reverse("a") -> reverse("") + 'a' -> ("") + 'a' -> "a"

These are the trivial examples, let's try it with longer strings:

reverse("ab")  -> reverse("b") + 'a'
reverse("abc") -> reverse("bc") + 'a'
               -> (reverse("c") + 'b') + 'a'
               -> ((reverse("") + 'c') + 'b') + 'a'
               -> ((("") + 'c') + 'b') + 'a'
               -> "cba"

The general pattern should be clear now. For the sake of completeness, let's manually "unroll" the recursive calls for a 4 character string:

reverse("abcd") -> reverse("bcd") + 'a'
                -> (reverse("cd") + 'b') + 'a'
                -> ((reverse("d") + 'c') + 'b') + 'a'
                -> (((reverse("") + 'd') + 'c') + 'b') + 'a'
                -> (((("") + 'd') + 'c') + 'b') + 'a'
                -> "dcba"

2 Comments

Oh, it's clear now. I was wrong because I thought that the method was self calling only with the str.substring(1) portion, aka (reverseString(str.substring(1))) + str.charAt(0). Thank you very much for your answer!
@PetarBrdaroski it is. The recursive call is only passed the "tail" of the string. The head is appended after the recursive call returns
0

It works like this:

reverseString("Peter") = 
        reverseString("eter") + P = 
                (reverseString("ter") + e) + P = 
                    ((reverseString("er") + t) + e) + P = 
                        (((reverseString("r") + e) + t) + e) + P = 
                            ((((reverseString("") + r) + e) + t) + e) + P =
                            (((("" + r) + e) + t) + e) + P =
                            ((((r) + e) + t) + e) + P =
                            (((r + e) + t) + e) + P = 
                            (((re) + t) + e) + P = 
                            ((re + t) + e) + P = 
                            ((ret) + e) + P = 
                            (ret + e) + P = 
                            (rete) + P = 
                            rete + P = 
                            reteP

1 Comment

Thank you so much for the broken down answer. Really appreciate the time and effort. It's all clear now!
0

On your example when your function reaches only one character like Peter when it becomes only "P" and the string is not empty you call

substring(1)

Which calls an index out of the range while the string only have P on index 0 and none on index 1 You have to put a base case that checks if the string length is equal to 1 or less

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.