While we are at it, let us write another recursive function - a function to reverse the characters of a string.
We take the string, some how we reverse last n-1 characters and then add the first character to the end.
Let us look at an example of reversing the 5 letter string Hello
The last call just returns the empty string. This returned value is available to previous call. This will return o. Then we go to the previous call of function which will add l to this and return lo. Then we move up the function stack and add l to this lo and return llo. And so on.
Here is the code
Write a recursive function to reverse a string
To reverse a string, we can use this algorithm
- If the string is not empty
- return substring of last n-1 characters +first character
We take the string, some how we reverse last n-1 characters and then add the first character to the end.
Let us look at an example of reversing the 5 letter string Hello
- Reverse Hello
- Reverse ello + H
- reverse llo+e
- reverse lo+l
- reverse o+l
- reverse ""+o
The last call just returns the empty string. This returned value is available to previous call. This will return o. Then we go to the previous call of function which will add l to this and return lo. Then we move up the function stack and add l to this lo and return llo. And so on.
Here is the code
String reverseString(String s){ if(!s.isEmpty()){ return reverseString(s.substring(1))+s.substring(0,1); }else return ""; }
Comments
Post a Comment