Palindrome Index

  • + 0 comments

    My Java solution:

    public static int palindromeIndex(String s) {
            //goal: find idx of char that will make str a palindrome when its removed
            if(s.length() == 1) return -1; //already a palindrome
            
            //use two pointers to iterate from left and right of str
            int left = 0, right = s.length() - 1;
            while(left < right){
               char leftChar = s.charAt(left);
               char rightChar = s.charAt(right);
               //if left pointer != right pointer, check which idx will make a palindrome if removed
               if(leftChar != rightChar){
                    if(isPalindrome(s, left + 1, right)) return left;
                    else return right;
               }
                left++;
                right--;
            }
            return -1; //str is already a palindrome
        }
        
        //uses two pointers to make sure chars are mirrored
        public static boolean isPalindrome(String s, int left, int right){
            while(left < right){
                if(s.charAt(left) != s.charAt(right)) return false; //chars arent mirrored
                left++;
                right--;
            }
            return true;
        }