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:
for an odd number of elements, or this pattern:
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:
Which gives you a "recursive algorithm" you could apply: pass the function a string
, it's length
, and the current check index
and you can compare substrings by comparing the character at index
with the character at index
(len - (n + 1))
If they are different, the string is not a palindrome, so you return
If they are the same, you call the same function with the index
increased by one.
Obviously, you need a check that you haven't checked all the elements - if you have, you return
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