简体   繁体   中英

StackOverflowError when trying to find the reverse of a string using recursion in java

I'm trying to use recursion to find the reverse of a string, but I get a stackoverflowerror when I run my code. I'm new to recursion so I'm not sure what I need to do to fix it.

public static String reverse(String string) {
        int index = 0;
        if(string == null){
            return " ";
        }
        else if(index < string.length()) {
            char a;
            a = string.charAt(index);
            index += 1;
            return a + reverse(string);
        }
        return " ";
    }

This is not how recursion should work, because you are just passing the same string over and over again. You could use recursion, but there are two approaches for your problem.

  1. Get the last character and call the method with a string that doesn't have the last character, like so:

     public String reverse(final String string) { if (string != null && !string.isEmpty()) { final int length = string.length(); final char character = string.charAt(length - 1)); final String result = reverse(string.substring(0, length - 2)); if (result != null) return String.valueOf(character) + result; return String.valueOf(character); } return null; } 

I should not that I have not tested this, but the point is that I am changing the string passed and have a mechanism to detect when to quit calling my own method.

The second method is to do this without recursion, because you can accomplish this with some for loops and such. But for the sake of learning, check 1 :P

The piece you seem to be missing is passing the index into your function. Also, you need to return the current character at the end when you recurse. I think you wanted something like

private static String reverse(String string, int index) {
    if (string != null && index < string.length()) {
        char a = string.charAt(index);
        return reverse(string, index + 1) + a;
    }
    return "";
}

Then your method in the public interface can call that function with an initial index of 0 like

public static String reverse(String string) {
    return reverse(string, 0);
}

Of course, in real code I would prefer StringBuilder and something like

public static String reverse(String string) {
    StringBuilder sb = new StringBuilder(string);
    return sb.reverse().toString();
}

There are a number of problems. I've added some comments to try to help.

public static String reverse(String string) {
    int index = 0;
    if(string == null){
        return " ";
    }
    /* This will always be true because index is always zero */
    else if(index < string.length()) {
        char a;
        /* This gets the character at position zero */
        a = string.charAt(index);
        /* This increments zero by 1 */
        index += 1;
        /* This takes the character and then calls reverse again (the recursion.
           The problem is that you are passing the full string in and so every time
           you recurse, index will be zero again and the string will be exactly the same length.
           So no exit criterion will ever be triggered. 
           As such this is an infinite recursion. */
        return a + reverse(string);
    }
    return " ";
}

I would suggest considering the following:

  • On the last recursive call, ie when you start to "pop back" through each of the recursive calls, what is it that you expect to trigger this?
  • If you decide that on every recursive call you are going to shorten the string by removing the first character, then the last call would be an empty string.
  • On the other hand, if you decide that your last call will be that the index variable equals the string length, then you will want to consider passing in an extra parameter (the index) and increasing this by one on every recursive call.

You're initializing variables "index and a" each time the recursive method get called. Initialize all of the variable outside the method block. Try this function..

public static String reverse(String str){

    if(str.length()<=0||str.length()==1)
        return str;
    return reverse(str.substring(1))+str.charAt(0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM