Answer the question
In order to leave comments, you need to log in
How to optimize the palindrome finding algorithm?
How to optimize this algorithm?
public void checkPalindrome(string number)
{
string value1 = null;
string value2 = null;
for (int i = 0; i < number.Length; i++)
{
value1 += number[i];
}
for(int q = number.Length; q > 0; q--)
{
value2 += number[q - 1];
}
string result = value1 == value2 ? "Yes, it's a Palindrome" : "No, it's not a Palindrome";
Console.WriteLine(result);
}
Answer the question
In order to leave comments, you need to log in
It is enough to go up to half of the string, comparing the initial characters with the final ones and completing the check on the first failure:
public void checkPalindrome(string input)
{
string result = isPolindrome(input) ? "Yes, it's a Palindrome" : "No, it's not a Palindrome";
Console.WriteLine(result);
}
private bool isPolindrome(string input)
{
int halfLength = input.Length / 2;
for (int i = 0; i < halfLength; i++)
{
if (input[i] != input[input.Length - i - 1])
return false;
}
return true;
}
so we get the best possible complexity O(n / 2) and Ω(1)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question