Translate

Saturday, 26 July 2014

Palindrome Algoritms

Palindrome is a pattern where irrespective of direction of access the semantics(meaning) remains same or in other way if the reverse of the Value or the String is same as the original then the Value or the String is called Palindrome.

This is Palindrome Algorithm in C function:

int palindrome_test(char str[], int len){
    int matches,match=0, x, y; // matches:
    y = len - 1 ;
 
    if(len % 2 == 0){
       matches = len/2;
    }else{
          matches = (len/2)+1;
    }
 
    for(x=0; x<matches; x++){
        if(str[x]=='\0'){
           break;
        }
        while(str[y]=='\0'){
              y--;
        }
        if(str[x]==str[y]){
           match++;
        }
           
      y--;    
    }

    if(match==matches){
       return 1;
    }
    else{
         return 0;
    }
}


Assume for simplicity that the palindrome is a length that is an odd number. Also, we treat a single character as a palindrome of length 1.

We store the possible matches for the specified string which is half the length of the string. We initially assumed that the palindrome had an odd length. This algorithm works for even palindromes as well. For each position in the string we store an upper and lower pointer that tracks the upper and lower bounds of the largest palindrome centered at that position. When match is the same value of matches we have a Palindrome.

No comments:

Post a Comment