Sometimes you can find a solution to the original problem by defining a recursive function to a problem similar to the original problem. This new method is called a recursive helper method. The original problem can be solved by invoking the recursive helper method.
The recursive isPalindrome method in RecursivePalindromeUsingSubstring.java is not efficient, because it creates a new string for every recursive call. To avoid creating new strings, you can use the low and high indices to indicate the range of the substring. These two indices must be passed to the recursive method. Since the original method is isPalindrome(String s), you have to create the new method isPalindrome(String s, int low, int high) to accept additional information on the string, as shown in the code below.
Two overloaded isPalindrome methods are defined. The first, isPalindrome(String s), checks whether a string is a palindrome, and the second, isPalindrome(String s, int low, int high), checks whether a substring s(low..high) is a palindrome. The first method passes the string s with low = 0 and high = s.length() – 1 to the second method. The second method can be invoked recursively to check a palindrome in an ever-shrinking substring. It is a common design technique in recursive programming to define a second method that receives additional parameters. Such a method is known as a recursive helper method.
Helper methods are very useful in designing recursive solutions for problems involving strings and arrays. The sections that follow give two more examples.
Discover more from Coursity
Subscribe to get the latest posts sent to your email.