I can’t stand threads about recursive functions.
@
cblack618
There isn’t anything special or scary about a recursive function. It is all in people’s heads.
Think it through:
Given two indices into a string (which asks for a
substring), you have a simple either/or question:
• Are the indices invalid?
• Are the indices valid?
If the indices are invalid (upper < lower), you are dealing with an empty substring — which is YES a palindrome. (The empty string is a palindrome.)
You can even extend this. Given a substring of length 1 (like "a") then you clearly have a palindrome. ("a" is a palindrome, just like "".)
You can revise your question:
• If (upper <= lower) then YES (it is a palindrome)
• else maybe?
Here is the basis of any recursive function. Test a terminal condition (in this case, can I say that I definitely do or do not have a palindrome) and terminate. Otherwise we have more questions to ask:
1 2 3 4 5
|
bool isPalindrom(string str, int lower, int upper)
{
if (upper <= lower) return true;
// else maybe?
}
|
Now we can consider the maybe part: do the characters at the indexed places match (does
str[lower] == str[upper]
)?
Let’s make this another question:
• do the two indexed characters match equal?
• do the two indexed characters match unequal?
If they are unequal, then you cannot have a palindrome.
Otherwise you are at another maybe.
1 2 3 4 5 6
|
bool isPalindrom(string str, int lower, int upper)
{
if (upper <= lower) return true;
// test the next possibility (is it NOT a palindrome?)
// else maybe?
}
|
But here is where life gets easy. You have already answered the question for the maybe!
Simply adjust the indices and ask the same palindrome questions again!
Eventually you will either find a mismatch (not a palindrome) or an empty/single-character string (yes a palindrome).
It takes a little practice being able to order the questions properly. For example, the first question, valid or invalid indices — we test whether they are invalid first because that gives us an immediate answer to the question “is-it-a-palindrome?”
If we had tested whether they were valid we would be playing with the “maybe” part, which is too much to think of first.
In other words, the questions we ask are designed to chip away at that maybe until there is nothing left. This is the point of recursion. Chip everything away until we can just keep asking the same questions over and over on a simpler or smaller piece of the problem.
madam
↑ ↑ it is not (not a palindrome)
↑↑↑ maybe it is
ada
↑ ↑ it is not (not a palindrome)
↑ maybe it is
d it is definitely a palindrome |
Hope this helps.