Reputation: 29
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);
}
}
Upvotes: 2
Views: 628
Reputation: 455
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.
Upvotes: 1
Reputation: 855
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));
}
Upvotes: 0
Reputation: 588
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
Upvotes: 0
Reputation: 7461
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.
Upvotes: 1
Reputation: 8906
Take, for example, string "ABCD".
backward(0)
{
backward(1)
{
backward(2)
{
backward(3)
{
print D
}
print C
}
print B
}
print A
}
Upvotes: 1
Reputation: 5260
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.
Upvotes: 2