Palindrome Index

  • + 0 comments

    Java solution:

     public static boolean isPalindrome(String s){
        int start = 0, end = s.length() - 1;
         while(start < end){
          if(s.charAt(start) != s.charAt(end))
            return false;
          start++;
          end--;
          } 
        return true;
        }
      
      public static int palindromeIndex(String s) {
        int start = 0, end = s.length() - 1;
    
        if(isPalindrome(s))
          return -1;
        
        while(start < end){
          int start_elem = s.charAt(start);
          int end_elem = s.charAt(end);
          
          if(start_elem != end_elem){
            String s_without_start = s.substring(start + 1, end + 1);
            if(isPalindrome(s_without_start))
              return start;
          
            String s_without_end = s.substring(start, end);
            if(isPalindrome(s_without_end))
              return end;  
            }
          start++;
          end--;
          }
        
        return -1; 
      }