Minimum cuts required to convert a palindromic string to a different palindromic string | Java program to solve the above problem ; Function to check if string is palindrome or not ; Function to check if it is possible to get result by making just one cut ; Appending last element in front ; Removing last element ; Checking whether string s2 is palindrome and different from s . ; If length is <= 3 then it is impossible ; Array to store frequency of characters ; Store count of characters in a array ; Condition for edge cases ; Return 1 if it is possible to get palindromic string in just one cut . Else we can always reached in two cuttings . ; Driver Code
import java . util . Arrays ; class GFG { static boolean isPalindrome ( String s ) { for ( int i = 0 ; i < s . length ( ) ; ++ i ) { if ( s . charAt ( i ) != s . charAt ( s . length ( ) - i - 1 ) ) { return false ; } } return true ; } static boolean ans ( String s ) { String s2 = s ; for ( int i = 0 ; i < s . length ( ) ; ++ i ) { s2 = s2 . charAt ( s2 . length ( ) - 1 ) + s2 ; s2 = s2 . substring ( 0 , s2 . length ( ) - 1 ) ; if ( ( s == null ? s2 != null : ! s . equals ( s2 ) ) && isPalindrome ( s2 ) ) { return true ; } } return false ; } static int solve ( String s ) { if ( s . length ( ) <= 3 ) { return - 1 ; } int cnt [ ] = new int [ 25 ] ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { cnt [ s . charAt ( i ) - ' a ' ] ++ ; } if ( Arrays . stream ( cnt ) . max ( ) . getAsInt ( ) >= ( s . length ( ) - 1 ) ) { return - 1 ; } else { return ( ans ( s ) ? 1 : 2 ) ; } } public static void main ( String [ ] args ) { String s = " nolon " ; System . out . println ( solve ( s ) ) ; } }