How do you check if a string is a palindrome?
Short answer: Compare characters from both ends moving inward: s[low] with s[high]. If any pair differs, it is not a palindrome. O(n) time, O(1) space.
#include <stdbool.h>
#include <string.h>
bool is_palindrome(const char *s)
{
size_t len = strlen(s);
if (len < 2) return true;
size_t low = 0, high = len - 1;
while (low < high) {
if (s[low] != s[high])
return false;
low++;
high--;
}
return true;
}
/* "ABCKCBA" -> true, "ABCA" -> false */
Finding the length. Counting with while (str[count] != '\0') count++; is fine and is exactly what strlen does. Use high = len - 1, not len: index len is the terminating '\0'.
Edge cases: empty string and one character are palindromes. With size_t, guard len < 2 before len - 1.
Variant: ignore case and non-letters ("A man, a plan, a canal: Panama"):
#include <ctype.h>
bool is_palindrome_alnum(const char *s)
{
size_t lo = 0, hi = strlen(s);
while (lo < hi) {
while (lo < hi && !isalnum((unsigned char)s[lo])) lo++;
while (lo < hi && !isalnum((unsigned char)s[hi - 1])) hi--;
if (lo < hi && tolower((unsigned char)s[lo]) != tolower((unsigned char)s[hi - 1]))
return false;
lo++; hi--;
}
return true;
}
The (unsigned char) cast matters: passing a negative char (bytes ≥ 0x80 on platforms where char is signed) to isalnum is undefined behaviour.
Follow-ups: palindrome number without converting to a string (reverse half the digits), and "is a linked list a palindrome" (find the middle, reverse the second half, compare).