Recursion means calling a function from itself, either directly or indirectly.
If you look at a palindrome, you can see that it's either this pattern:
ABCDEDCBA
for an odd number of elements, or this pattern:
ABCDDCBA
for an even number of elements.
So you can think of it as a "set" of strings nested inside each other, all of which must be a palindrome in order for the whole to be:
ABCDEDCBA
BCDEDCB
CDEDC
DED
E
Or
ABCDDCBA
BCDDCB
CDDC
DD
Which gives you a "recursive algorithm" you could apply: pass the function a string
str
, it's length
len
, and the current check index
n
and you can compare substrings by comparing the character at index
n
with the character at index
(len - (n + 1))
If they are different, the string is not a palindrome, so you return
false
If they are the same, you call the same function with the index
n
increased by one.
Obviously, you need a check that you haven't checked all the elements - if you have, you return
true
.
That'll work. But ... it's a very poor idea to apply recursion to this kind of problem (just as it is for factorials and most other "school homework" examples) as each time you call a function, you take up memory on the Stack - which is not infinite, in fact it's pretty small. If you use up all the stack space, your app will crash, and it doesn't take a particularly long string you want to check to use up the whole stack!
Recursion is a powerful technique, but it needs to be applied sensibly: just because you
can do something, doesn;t mean you
should!