Palindrome Index

  • + 0 comments

    // java solution

    private static int findIndexOfMismatch(String s) { for(int i=0 ; i

    public static int palindromeIndex(String s) {
        int mismatchIndex = findIndexOfMismatch(s);
        if(mismatchIndex==-1) {
            // is already a palindrome
            return -1;
        }
    
        // option 1 - remove mismatching char at the left and check
        String maybePalindrome = s.substring(mismatchIndex+1, s.length()-mismatchIndex);
        if(findIndexOfMismatch(maybePalindrome)==-1) {
            return mismatchIndex;
        }
    
        // option 2 - remove mismatching char at the right and check
        maybePalindrome = s.substring(mismatchIndex, s.length()-mismatchIndex-1);
        if(findIndexOfMismatch(maybePalindrome)==-1) {
            return s.length()-mismatchIndex-1;
        }
    
        // option 3 - removing one char is not enough to make this into a palindrome
        return -1;
    }