[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));
}
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?
[Update]
This variation adds a single line of regex to comply with the dictionary form of Palindrome.
I also added a couple of unit tests to make sure it works:
Assert.IsTrue(IsPalindrome("ab cb a"),"ab cb a");
Assert.IsTrue(IsPalindrome("A man, a plan, a canal,
private bool IsPalindrome(string text)
{
if(text==null){
return false;
}
text=text.ToLower();
//remove whitespace and other non numeric chars
text = Regex.Replace(text,@"[\s\W]",string.Empty);
char[] backwards = text.ToCharArray();
Array.Reverse(backwards);
return (new string( backwards)== text);
}