A few days ago I was asked by mail a program to tell us if a string is palindrome or not, but using arecursive function . I found it interesting but rarely asked to do so recursively.
You may remember that I had posted here a way to tell if a string is palindrome or not , which I discovered (now that I did this one) that is not very efficient.
Well the code is this:
The truth is that it is the recursive function is a miracle. What I did was to change the cycle to check that the characters were the same at a function in which a variable is increased each time you call itself.
The code is now more efficient for two simple reasons:
- He stops and gives the result to the first comparison of characters that are not equal. If the first and last characters are not equal, it is no longer palindrome and continues to examine others.
- Czech only half of the characters. If half of the characters correspond to the configuration of a palindrome, and no further analysis of why the other half.
Perhaps a better way to do this with a function that receives the string to analyze, compare the first and last character, if not, is not, if yes, remove the first and last character and call back function. This until the number of comparisons is equal to some half of the initial length of the string. Anyone is encouraged to do so?
0 comments:
Post a Comment