简体   繁体   中英

Reversing a String using recursion in Java

I am currently getting my head around recursion in Java. Having come across the below code, I can't work out how the recursive method produces the reverse String. Any explanation would be appreciated!

class Backwards {
    String str;

    Backwards(String s) {
        str = s;
    }

    void backward(int idx) {
        if(idx != str.length()-1) {
            backward(idx+1);
        }
        System.out.print(str.charAt(idx));
    }
}

class BWDemo {
    public static void main(String args[]) {

        Backwards s = new Backwards("This is a test");
        s.backward(0);
    }
}

If you debug it, with pen and paper, it would be simple to see what is going on.

Basically - it go to the end of the string and start printing char by char from the end to the start.

Look at the backward method. What it does? Step by step:

  1. If that's not last character (index of last character), you're invoking this function at the next character index
  2. Prints out the current character.

So, if we're expanding recursive calls, it would be (for string "hel"):

  1. call backward(0) (which will at the end print 0-th character)
  2. it would call backward(1) (which will at the end print 1-st character)
  3. it would call backward(2) (...)
  4. there recursive call would not be called as 2-nd charater is the last
  5. the third call will end after printing last characted: "l"
  6. the the control would go to the previous call, which would output "e"
  7. control would go to the first backward call, which will output "h"

Visualization: 可视化

So, the final output is "leh", which is what we want.

Take, for example, string "ABCD".

backward(0)
{
  backward(1)  
  {
    backward(2)
    {
      backward(3)
      {
        print D
      }
      print C
    } 
    print B
  }
  print A
}

Try this:

private static String reverse(String str) {

    if (str == null || str.length() == 0) return "";

    return str.toCharArray()[str.length() - 1] + reverse(str.substring(0, str.length() - 1));
}

hope it will help.

Take a look at the method backward.

void backward(int idx) {
if(idx != str.length()-1) {
    backward(idx+1);
}
System.out.print(str.charAt(idx));

}

It takes an index number and prints the character that is in that index position. Then it calls it self again (that's why it is recursive) but now with the index incremented by 1, because you want to print the next character - backward(idx+1);

Look at the effect of different index numbers:

Backwards s = new Backwards("test");

Index = 0 s.backward(0); output: tset

Index = 1 s.backward(1); output: tse

Index = 2 s.backward(2); output: ts

Your class:

public class Backwards {
    String str;

    Backwards(String s) {
        str = s;
    }

    String backward(int i) {
        int j = i+1;
        if(i <= str.length())
            return str.charAt(str.length()-i) + backward(j);
        return "";
    }
}

At the main:

public static void main(String[] args) {

    Backwards s = new Backwards("This is a test");
    System.out.println(s.backward(1));

}

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