6 Comments

  • Nice refactoring! :-)



    As a TDDer, expressing the rules with Asserts just makes so much sense - nice to see others think the same!



    I have always thought of palindromes as being more loose, such as:



    Madam I'm Adam



    Although I guess this would simply require same-casing everything and removing whitespace and punctuation ...

  • Uhm, how about this?



    private bool IsPalindrome(string text)

    {

    if(text==null) return false;

    text=text.ToLower();

    string backwards=Microsoft.VisualBasic.StrReverse(text);

    return (backwards==text);

    }


  • "X" == "X" ? Or "X".Equals( "X" ) ?

  • As per the original algorithm

    just modifying a little, i like the idea of going half way than using string operations which are expensive



    char[] a = text.ToCharArray();

    bool b = true;

    int l = a.length;

    int i =0;

    while ( b && i < l/2 )

    {

    if ( !(a[i] == a[l-i-1]) ) b=false;

    i++;

    }

    return b;



  • You should probably get rid of white space first. Generally people don't consider white space in palindromes.

  • Mani's solution is good, but why create a character array unnecessarily, and why keep looping when you've established they're different? The string class already has an indexer so you can do:

    if (text[i] == test[l-i-1])



    You could generalize it to ignore whitespace and punctuation (air code) ...



    int firstIndex = 0;

    int lastIndex = text.Length-1;

    while(firstIndex < lastIndex)

    {

    // Ignore punctuation and whitespace

    if (Char.IsPunctuation(text[firstIndex]) || Char.IsWhiteSpace(text[firstIndex]))

    {

    firstIndex++;

    continue;

    }

    if (Char.IsPunctuation(text[lastIndex]) || Char.IsWhiteSpace(text[lastIndex]))

    {

    lastIndex--;

    continue;

    }

    if (Char.ToLower(text[firstIndex]) != Char.ToLower(text[lastIndex])) return false;

    firstIndex++;

    lastIndex--;

    }

    return true;



Comments have been disabled for this content.