Palindrome Index

  • + 0 comments

    Below is my C# solution with explaination in comments. Hope you find it useful.

    public static int palindromeIndex(string s)
    {
        for (int i = 0, j = s.Length - 1; i < j; i++, j--)
        {
            if (s[i] != s[j])
            {
                // remove 1 char at i or j
                // then check for condition
                // if false -> do not need to check the remain positions
                // because it can not be palindrome anymore
                // return -1
                if (CheckPalindrome(s, i + 1, j)) return i; //remove at position i & check
                if (CheckPalindrome(s, i, j - 1)) return j; //remove at position j & check
                return -1; // there is no solution
            }
        }
        return -1; // it's palindrome already  
    }
    public static bool CheckPalindrome(string s, int left, int right)
    {
        for (int i = left, j = right; i < j; i++, j--)
        {
            if (s[i] != s[j]) return false;
        }
        return true;
    
    }