Skip to content

Instantly share code, notes, and snippets.

@rushfrisby
Created August 21, 2014 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rushfrisby/ff6039c23bf203b10b91 to your computer and use it in GitHub Desktop.
Save rushfrisby/ff6039c23bf203b10b91 to your computer and use it in GitHub Desktop.
Check if a string is a palindrome - popular interview question!
class Program
{
static void Main(string[] args)
{
const string mom = "mom";
const string mother = "mother";
const int iterations = 10000;
var sw = new Stopwatch();
sw.Start();
for (var i = 0; i < iterations; i++)
{
IsPalindrome(mom);
IsPalindrome(mother);
}
sw.Stop();
Console.WriteLine("short: " + sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
for (var i = 0; i < iterations; i++)
{
IsPalindromeLong(mom);
IsPalindromeLong(mother);
}
sw.Stop();
Console.WriteLine("long: " + sw.ElapsedMilliseconds);
Console.Read();
}
static bool IsPalindrome(string word)
{
if(word==null) throw new ArgumentNullException("word");
return String.Equals(word, new string(word.Reverse().ToArray()), StringComparison.CurrentCultureIgnoreCase);
}
//about twice as fast
static bool IsPalindromeLong(string word)
{
if (word == null) throw new ArgumentNullException("word");
var i = 0;
var j = word.Length - 1;
while (true)
{
if (i > j)
{
return true;
}
var a = word[i];
var b = word[j];
if (char.ToLower(a) != char.ToLower(b))
{
return false;
}
i++;
j--;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment