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:
So, if we're expanding recursive calls, it would be (for string "hel"):
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.