Given a string. The task is to check if the string is a palindrome or not using pointers. You are not allowed to use any built-in string functions. A string is said to be a palindrome if the reverse of the string is same as the original string. For example, “madam” is palindrome because when the string is reversed same string is achieved, but “Madam” is not a palindrome.
Input: str = "Madam"
Output: String is not a Palindrome.
Input: str = "madam"
Output: String is Palindrome.
Input: str = "radar"
Output: String is Palindrome.
Algorithm:
- Take two pointers say, ptr and rev.
- Initialize ptr to the base address of the string and move it forward to point to the last character of the string.
- Now, initialize rev to the base address of the string and start moving rev in forward direction and ptr in backward direction simultaneously until middle of the string is reached.
- If at any point the character pointed by ptr and rev does not match, then break from the loop.
- Check if ptr and rev crossed each other, i.e. rev > ptr. If so, then the string is palindrome otherwise not.
Below is the implementation of the above approach:
C
#include <stdio.h>
void isPalindrome( char * string)
{
char *ptr, *rev;
ptr = string;
while (*ptr != '\0' ) {
++ptr;
}
--ptr;
for (rev = string; ptr >= rev;) {
if (*ptr == *rev) {
--ptr;
rev++;
}
else
break ;
}
if (rev > ptr)
printf ( "String is Palindrome" );
else
printf ( "String is not a Palindrome" );
}
int main()
{
char str[1000] = "madam" ;
isPalindrome(str);
return 0;
}
|
OutputString is Palindrome
Complexity Analysis:
- Time Complexity: O(N), where N represents the length of the given string.
- Auxiliary Space: O(1), no extra space is required, so it is a constant.