Palindrome Index

  • + 0 comments

    C# failed first tests using if(s == s,Reverse()) It was too slow for the tests - I'd still use it in production for readability though. Here's the final:

    public static int palindromeIndex(string s)
    {
        int stringLength = s.Length;            
        int returnPos = 0;
    
        if (IsReversible(s))
            return -1;
    
        for (int i = 0; i < stringLength/2; i++)
        {
            if (s[i] != s[stringLength-i-1])
            {
                returnPos = RemoveCharacterAndTest(s, i);
                if (returnPos>-1)
                    return returnPos;
            }
        }
        return -1;
    }
    
    private static int RemoveCharacterAndTest(string s, int removeAt)
    {
        string testString = s.Remove(removeAt,1);
        int returnPos = 0;
        if (IsReversible(testString))
            return removeAt;
    
        testString = s.Remove(s.Length - removeAt - 1, 1);
        if (IsReversible(testString))
        {
            returnPos = (s.Length - removeAt - 1);
            return returnPos;
        }                
        return -1;
    }
    
    private static bool IsReversible(string s)
    {
        int strLength = s.Length;
        for (int i = 0; i < strLength / 2; i++)
        {
            if (s[i] != s[strLength - i - 1])
                return false;
        }
        return true;
    }