Saturday, January 19, 2013

Program to Check whether the given string is palindrome or not .

There are two ways . One method is by using stack and second method is by comparing characters 1,n(length of the string) and 2,n-1 and so. For first method space complexity is O(n) . But for the second method  space complexity is O(1) .So it is better to use the second method. And the time complexity for both method is O(n)

Code: (in C)
int is_palindrome(char *str)
{
          if(str==NULL)
                  return 0;
          int len = strlen(str),i=0,j=len-1;
          while (i  < j)
          {
                 if(str[i]!=str[j])
                       return 0;
                 i++;
                 j--;
            }
           return 1;
}

Input   :  ababa
Output : 1

Please let me know if there is any bug in the above code and your suggestions are always welcome .

No comments: