[Test]
public void TestPelindromSimple()
{
Assert.IsTrue(IsPalindrome("a"),"a");
Assert.IsFalse(IsPalindrome("ab"),"ab");
Assert.IsTrue(IsPalindrome("aba"),"aba");
Assert.IsFalse(IsPalindrome("abc"),"abc");
Assert.IsTrue(IsPalindrome("abba"),"abba");
Assert.IsFalse(IsPalindrome("abbc"),"abbc");
Assert.IsTrue(IsPalindrome("abcba"),"abcba");
Assert.IsFalse(IsPalindrome("abcbc"),"abcbc");
Assert.IsTrue(IsPalindrome("lelelel"),"lelelel");
Assert.IsFalse(IsPalindrome("lele4el"),"lele4el");
Assert.IsFalse(IsPalindrome(null),"null");
Assert.IsTrue(IsPalindrome("ABba"),"ABba");
}
private bool IsPalindrome(string text)
{
if(text==null)
{
return false;
}
if(text.Length==1)
{
return true;
}
text=text.ToLower();
int firsthalfIndex = (text.Length/2);
int secondHalfIndex= (text.Length/2);
if(text.Length%2!=0)
{
secondHalfIndex+=1;
}
char[] part1 = text.Substring(0,firsthalfIndex).ToCharArray();
char[] part2 = text.Substring(secondHalfIndex).ToCharArray();
Array.Reverse(part2);
return (new string( part1)== new string(part2));
}
I liked what I had but then it occurred to me: all these test can pass with this simple routine:
private bool IsPalindrome(string text)
{
if(text==null)
{
return false;
}
text=text.ToLower();
char[] backwards = text.ToCharArray();
Array.Reverse(backwards);
return (new string( backwards)== text);
}
Ain't life funny?