0
I can't understand this code.Could anyone explain to me?
public class Main { static String rev(String str){ return str.length()<2?str:rev(str.substring(1))+str.charAt(0); } public static void main(String[] args) { String string="edon"; System.out.println(rev(string)); } }
2 Respostas
+ 2
Suppose rev actually correctly reverses a string.
Then a string "edon" is returned as the reverse of "don", which is the substring from index 1, and reverses to "nod" and concatenate with the first char, which is 'e'. So, it returns "node".
So far we have seen that if a string of length n reverses correctly, so does a string of length (n+1). And for a string of length 1, or < 2, it returns the string, which certainly is itself reversed. So, it is reversing strings of length 1, thus also strings of length 2. Thus strings of length 3, thus of length 4, and so on. In short, it reverses a string of any finite length.
A classic example of a recursive algorithm that solves a problem through a solution of the same problem but of smaller size.
+ 1
rev("n")
rev("on")
rev("don")
This is how your stack call would look like.
"n" -> returned from top
"no" -> here onwards charAt(0) will come
"don"
"node"
After the end of call stack you would get your string in reverse order.