It can be defined in steps:
- Split any string into first character and the '
rest'.
If the 'rest' length is greater than 0, then repeat step 1 for input 'rest'
When the recursion will get to the last character, it will start to print the characters in reverse.
The last recursive execution will return a empty string. To this empty statement it will add character from the previous call (n-1 character), then to this it will add character from position (n-2), and so on. This way we will get a recursive function:
public static String reverse(String a){
if(a.length()>0){
return reverse(a.substring(1))+a.charAt(0);
}
return ""; // last statement
}
Example:
'cat' -> reverse('at') + 'c'
(reverse('t') + 'a') + 'c'
((reverse('') + 't') + 'a' + 'c')
=> 'tac'