How to check if a string is a palindrome

A palindrome is a string that reads the same backward as forward. For instance, level, baab

To check if a string is a palindrome, you can reverse it and compare it with the original one.

  • if the reversed string is equal to the original. It means the input string is a palindrome.

Another approach would be to compare characters from both sides, one by one.

  • if all characters are equal, the input string is a palindrome.

 

palindrome

 

Code

    public bool IsPalindrome(string value)
    {
        int left = 0;
        int right = value.Length - 1;
        while (left < right)
        {
            if (value[left] != value[right])
            {
                return false;
            }

            left++;
            right--;
        }

        return true;
    }

The time complexity is O(n).