Palindrome

Answer to: http://forum.codecall.net/c-c/22050-palindrome-anyone.html

Determining if a string is a palindrome is a common beginner computer sciences question. For some reason, the majority of the answers I see involve creating a reversed copy of the string and comparing them. A faster, straightforward approach is to use two pointers, one from the head (or beginning) of the string and another from the tail (or end) of the string.

+-----+
|     |
RACECAR

 +---+
 |   |
RACECAR

  +-+
  | |
RACECAR

   +
   |
RACECAR

Quick and dirty example of what I mean…

#include <stdio.h>
#include <string.h>
 
int IsPal(const char* word){
    char *tail,*head = (char*)word;
 
    tail = head + strlen(word) - 1;
 
    while(tail >= head && *head != '\0'){
        if(*head++ != *tail--)
            return 0;
    }
    return 1;
}
 
int main(const int argv, const char* argc[]){
    int i;
 
    for(i = 1; i < argv; i++){
        printf("'%s' %s a palindrome.\n",argc[i],(IsPal(argc[i]) ? "is" : "is not"));
    }
    return 0;
}

You can use this little program by passing the words as arguments…

$ gcc pal.c -o pal
$ ./pal racecar lol fail
'racecar' is a palindrome.
'lol' is a palindrome.
'fail' is not a palindrome.

Answer To: http://forum.codecall.net/c-c/23169-spaces-check-palindrome-checking-recursive-algo.html

This is an adaptation of the above code to work on multi-word palindromes as well.

#include <stdio.h>
#include <string.h>
 
int IsPal(const char* word){
    const char *tail,*head = word;
 
    tail = head + strlen(word) - 1;
 
    while(tail >= head && *head != '\0'){
        if(*head == ' '){
            head++;
            continue;
        }
        if(*tail == ' '){
            tail--;
            continue;
        }
        if(*head++ != *tail--)
            return 0;
    }
    return 1;
}
 
int main(const int argv, const char* argc[]){
    int i;
 
    for(i = 1; i < argv; i++){
        printf("'%s' %s a palindrome.\n",argc[i],(IsPal(argc[i]) ? "is" : "is not"));
    }
    return 0;
}

Example output:

tyler@DeskMonster:~$ gcc pal.c ; ./a.out "a man a plan a canal panama" racecar fail
'a man a plan a canal panama' is a palindrome.
'racecar' is a palindrome.
'fail' is not a palindrome.
 
palindrome.txt · Last modified: 2010/01/09 15:43 (external edit)
 
Except where otherwise noted, content on this wiki is licensed under the following license:Public Domain
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki