Created
August 21, 2014 17:36
-
-
Save rushfrisby/ff6039c23bf203b10b91 to your computer and use it in GitHub Desktop.
Check if a string is a palindrome - popular interview question!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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