You can view the code and corresponding findings below:
This method proved to be one of the most efficient which followed the divide and conquer logic:
public static bool Check(string word)This method still has a room for improvement in terms of efficiency by going into the roots of char array instead of using its wrapper string type. This gives the fastest method to calculate the palindrome. So our new method is:
{
// Check length of the string for even or odd
var length = word.Length;
if (word == null || length == 0)
{
return false;
}
for (var i = 0; i < length / 2; i++)
{
if (word[i] != word[(length - 1) - i])
{
return false;
}
}
return true;
}
public static bool Check1(char[] word)But the easiest way to determine a word as a palindrome will be by the following piece of code:
{
// Check length of the string for even or odd
var length = word.Length;
if (word == null || length == 0)
{
return false;
}
for (var i = 0; i < length / 2; i++)
{
if (word[i] != word[(length - 1) - i])
{
return false;
}
}
return true;
}
public static bool Check2(string word)It's short and sweet but beware this is the costliest one since it reverses the string first which requires traversing through all the characters in the string!!!Finally, just for fun I tried a recursive algorithm which turns to be faster than the method defined just above for smaller strings but for larger strings it will be costlier because the deeper it goes the more memory it requires.
{
return (word.Equals(word.Reverse()));
}
public static bool Check3(string word)
{
return CheckRecursive(0, word.Length - 1, word);
}
public static bool CheckRecursive(int first, int last, string word)
{
if (word[first] != word[last] || first > last)
return false;
else if (word[first] == word[last])
{
CheckRecursive((first + 1), (last - 1), word);
return true;
}
return false;
}
No comments:
Post a Comment