String: Palindrome Check

Problem: Find if a given string is a palindrome. Palindrome is a word or a phrase that reads the same in either direction.
Ex: A man, a plan, a canal, panama!
Punctuation and spaces can be ignored.

Solution: The solution is pretty straight forward and involves comparing the characters at both ends, incrementally moving towards the center of the string. This is similar logic we used for reversing a string in place. The IsPalindrome method implemented below assumes that the string has been cleaned off of the punctuation characters and spaces.

Code:
bool IsPalindrome(char str[])
{
    int len = strlen(str);

    for(int i=0, j=len-1; i<j; i++, j--)
    {
        if(str[i] != str[j])
            return false;
    }
   return true;
}

No comments:

Post a Comment