Search code examples
crecursionpalindrome

Recursive function finding Palindrome


May be you can tell me the way, that I can start with, at least. I can use only C language. The task have very specific limitations and I can't break them in any way. The task is:

  • Write recursive function that checks if string is Palindrome.
  • Can use strlen() only once in function.
  • Can't use any loops or functions based on loops.
  • Can use only one transition in recursive function.
  • Can change the string, but only if it will come back in the end of function.
  • Declaration of function is: int palindrom(char* str);
  • I started to write, but have no ideas anymore:

    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <string.h>
    
    int palindrom(char* str)
    {
        int len = strlen(str);
        if (str[0] != str[len - 1]) return 0;
    
    }
    
    int main(void)
    {
        char string1[] = "ROTATOR";
        char string2[] = "8536358";
        char string3[] = "Palindrome";
        if (palindrom(string1)) printf("%s is Palindrome\n", string1);
        else printf("%s is not Palindrome\n", string1);
        if (palindrom(string2)) printf("%s is Palindrome\n", string2);
        else printf("%s is not Palindrome\n", string2);
        if (palindrom(string3)) printf("%s is Palindrome\n", string3);
        else printf("%s is not Palindrome\n", string3);
        return 0;
    }
    

Solution

  • The clue to how to solve is in the restriction: Can change the string, but only if it will come back in the end of function. That condition is checked by printing the result.

    #include <stdio.h>
    #include <string.h>
    
    int palindrom(char* str)
    {
        size_t len = strlen(str);
        int res;
        if(len < 2) {
            return 1;                   // cannot shorten: must be success
        }
        if(str[0] != str[len - 1]) {    // make palindrome test
            return 0;
        }
    
        str[len - 1] = '\0';            // shorten the string at the back
        res = palindrom(str + 1);       // recurse woth string shortened at the front
        str[len - 1] = str[0];          // replace last char (we know it's the same)
        return res;
    }
    
    int main(void)
    {
        char string1[] = "ROTATOR";
        char string2[] = "8536358";
        char string3[] = "Palindrome";
        char string4[] = "A";
        char *wrd[] = { "not ", "" };
    
        printf("%s is %sa Palindrome\n", string1, wrd[ palindrom(string1) ]);
        printf("%s is %sa Palindrome\n", string2, wrd[ palindrom(string2) ]);
        printf("%s is %sa Palindrome\n", string3, wrd[ palindrom(string3) ]);
        printf("%s is %sa Palindrome\n", string4, wrd[ palindrom(string4) ]);
    
        return 0;
    }
    

    Program output:

    ROTATOR is a Palindrome
    8536358 is a Palindrome
    Palindrome is not a Palindrome
    A is a Palindrome