Alex Rivera | Logout

How to check if the given string is palindrome?

Asked 2008-09-09T14:24:27.053
56

Definition:

A palindrome is a word, phrase, number or other sequence of units that has the property of reading the same in either direction

How to check if the given string is a palindrome?

This was one of the FAIQ [Frequently Asked Interview Question] a while ago but that mostly using C.

Looking for solutions in any and all languages possible.

Edit
Report

8 Answers

30

Language agnostic meta-code then...

rev = StringReverse(originalString)
return ( rev == originalString );
answered 2008-09-09T14:29:58.880
10

C in the house. (not sure if you didn't want a C example here)

bool IsPalindrome(char *s)
{
    int  i,d;
    int  length = strlen(s);
    char cf, cb;

    for(i=0, d=length-1 ; i < length && d >= 0 ; i++ , d--)
    {
        while(cf= toupper(s[i]), (cf < 'A' || cf >'Z') && i < length-1)i++;
        while(cb= toupper(s[d]), (cb < 'A' || cb >'Z') && d > 0       )d--;
        if(cf != cb && cf >= 'A' && cf <= 'Z' && cb >= 'A' && cb <='Z')
            return false;
    }
    return true;
}

That will return true for "racecar", "Racecar", "race car", "racecar ", and "RaCe cAr". It would be easy to modify to include symbols or spaces as well, but I figure it's more useful to only count letters(and ignore case). This works for all palindromes I've found in the answers here, and I've been unable to trick it into false negatives/positives.

Also, if you don't like bool in a "C" program, it could obviously return int, with return 1 and return 0 for true and false respectively.

answered 2008-09-09T22:01:54.647
6

I'm seeing a lot of incorrect answers here. Any correct solution needs to ignore whitespace and punctuation (and any non-alphabetic characters actually) and needs to be case insensitive.

A few good example test cases are:

"A man, a plan, a canal, Panama."

"A Toyota's a Toyota."

"A"

""

As well as some non-palindromes.

Example solution in C# (note: empty and null strings are considered palindromes in this design, if this is not desired it's easy to change):

public static bool IsPalindrome(string palindromeCandidate)
{
    if (string.IsNullOrEmpty(palindromeCandidate))
    {
        return true;
    }
    Regex nonAlphaChars = new Regex("[^a-z0-9]");
    string alphaOnlyCandidate = nonAlphaChars.Replace(palindromeCandidate.ToLower(), "");
    if (string.IsNullOrEmpty(alphaOnlyCandidate))
    {
        return true;
    }
    int leftIndex = 0;
    int rightIndex = alphaOnlyCandidate.Length - 1;
    while (rightIndex > leftIndex)
    {
        if (alphaOnlyCandidate[leftIndex] != alphaOnlyCandidate[rightIndex])
        {
            return false;
        }
        leftIndex++;
        rightIndex--;
    }
    return true;
}
answered 2008-09-09T19:14:26.013
2

This Java code should work inside a boolean method:

Note: You only need to check the first half of the characters with the back half, otherwise you are overlapping and doubling the amount of checks that need to be made.

private static boolean doPal(String test) {
    for(int i = 0; i < test.length() / 2; i++) {
        if(test.charAt(i) != test.charAt(test.length() - 1 - i)) {
            return false;
        }
    }
    return true;
}
answered 2008-09-09T14:39:06.613
2

Another C++ one. Optimized for speed and size.

bool is_palindrome(const std::string& candidate) {
    for(std::string::const_iterator left = candidate.begin(), right = candidate.end(); left < --right ; ++left)
        if (*left != *right)
            return false;
    return true;
}

answered 2008-09-09T15:27:03.050
1

In Ruby, converting to lowercase and stripping everything not alphabetic:

def isPalindrome( string )
    ( test = string.downcase.gsub( /[^a-z]/, '' ) ) == test.reverse
end

But that feels like cheating, right? No pointers or anything! So here's a C version too, but without the lowercase and character stripping goodness:

#include <stdio.h>
int isPalindrome( char * string )
{
    char * i = string;
    char * p = string;
    while ( *++i ); while ( i > p && *p++ == *--i );
    return i <= p && *i++ == *--p;
}
int main( int argc, char **argv )
{
    if ( argc != 2 )
    {
        fprintf( stderr, "Usage: %s <word>\n", argv[0] );
        return -1;
    }
    fprintf( stdout, "%s\n", isPalindrome( argv[1] ) ? "yes" : "no" );
    return 0;
}

Well, that was fun - do I get the job ;^)

answered 2008-09-09T16:47:15.183
1

Python:

if s == s[::-1]: return True

Java:

if (s.Equals(s.Reverse())) { return true; }

PHP:

if (s == strrev(s)) return true;

Perl:

if (s == reverse(s)) { return true; }

Erlang:

string:equal(S, lists:reverse(S)).
answered 2008-09-11T10:14:27.340
1

c++:

bool is_palindrome(const string &s)
{
    return equal( s.begin(), s.begin()+s.length()/2, s.rbegin());
}
answered 2008-10-23T06:16:13.133

Your Answer