Dec 16, 2011

Whether it is palindrome or not, recursively


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:
 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 # Include <string.h>
 # Include <iostream>
 using namespace std;
 cadenaf char [50] = {0}, int len, n = 0;

 chk4palindrosity string (int c)
 {
     if (cadenaf [c] == cadenaf [len - 1 - c])
     {
         n + +;
         if (n == len / 2)
             return "If palindrome!"
         chk4palindrosity return (c + 1);
     }
     else
         return "is not palindrome";
 }

 int main ()
 {
     char string [50], * part;
     court <<"Enter a palindrome:"; cin. getline (string, 50, '\ n');

     part = strtok (string, "") / /
     strcat (cadenaf, part) / /
     while ((part = strtok (NULL, ""))! = NULL) / /
         strcat (cadenaf, part) / / remove spaces from string

     len = strlen (cadenaf);
     court <<chk4palindrosity (0);
     cin. get ();
 } 
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:
  1. 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.
  2. 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

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Premium Wordpress Themes