Palindrome Index

  • + 0 comments

    Here is my solution. so before code this. i am trying to imagine how the palindrome works. and i found that. you only need to check first wrong character (first wrong from left, and first wrong from right)

    then what i do next ? I try to remove wrong character in left, check whether it is already palindrome. if no then i try to remove wrong character in right. if it is still not palindrome then there is no solution.

    public static int palindromeIndex(String s) {
    // Write your code here
        int leftWrongIndex = -1;
        int rightWrongIndex = -1;
        int sLength = s.length();
        for(int i=0; i < sLength/2; i++) {
            if(s.charAt(i) != s.charAt(sLength - 1 - i)) {
                leftWrongIndex = i;
                rightWrongIndex = sLength -1 -i;
                break;
            }
        }
        if(leftWrongIndex == -1 && rightWrongIndex == -1) {
            return -1;
        }
    
        if (checkPalindrome(s.substring(leftWrongIndex + 1, rightWrongIndex + 1))) {
            return leftWrongIndex;
        } else if (checkPalindrome(s.substring(leftWrongIndex, rightWrongIndex))) {
            return rightWrongIndex;
        }
    
        return -1;
    }
    
    public static boolean checkPalindrome(String s) {
        int sLength = s.length();
        for(int i=0; i< s.length() /2 ;i ++) {
            if(s.charAt(i) != s.charAt(sLength - 1 - i)) {
                return false;
            }
        }
        return true;
    }