C
C
CallMeYourDaddy2020-08-24 08:59:04
C++ / C#
CallMeYourDaddy, 2020-08-24 08:59:04

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

1 answer(s)
D
Dmitry Belyaev, 2020-08-24
@CallMeYourDaddy

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 question

Ask a Question

731 491 924 answers to any question