Java Reference
In-Depth Information
}
You should still supply a method to solve the whole problemÈŒthe user of your
method shouldn't have to know about the trick with the substring positions. Simply
call the helper method with positions that test the entire string:
public boolean isPalindrome()
{
return isPalindrome(0, text.length() - 1);
}
Note that this call is not a recursive method. The isPalindrome() method calls
the helper method isPalindrome(int, int) . In this example, we use
overloading to d efine two methods with the same name. The isPalindrome
method withou t parameters is the method that we expect the public to use. The
second method, with two int parameters, is the recursive helper method. If you
prefer, you can avoid overloaded methods by choosing a different name for the helper
method, such as substringIsPalindrome .
601
602
Use the technique of recursive helper methods whenever it is easier to solve a
recursive problem that is slightly different from the original problem.
S ELF C HECK
5. Do we have to give the same name to both isPalindrome methods?
6. When does the recursive isPalindrome method stop calling itself?
13.4 The Efficiency of Recursion
As you have seen in this chapter, recursion can be a powerful tool to implement
complex algorithms. On the other hand, recursion can lead to algorithms that perform
poorly. In this section, we will analyze the question of when recursion is beneficial
and when it is inefficient.
Consider the Fibonacci sequence introduced in Exercise P6.4: a sequence of numbers
defined by the equation
Search WWH ::




Custom Search