Minimum cuts required to convert a palindromic string to a different palindromic string | 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
function isPalindrome ( s ) { for ( let i = 0 ; i < s . length ; ++ i ) { if ( s [ i ] != s [ s . length - i - 1 ] ) { return false ; } } return true ; } function ans ( s ) { let s2 = s ; for ( let i = 0 ; i < s . length ; ++ i ) { s2 = s2 [ s2 . length - 1 ] + s2 ; s2 = s2 . substring ( 0 , s2 . length - 1 ) ; if ( ( s == null ? s2 != null : ! s == ( s2 ) ) && isPalindrome ( s2 ) ) { return true ; } } return false ; } function solve ( s ) { if ( s . length <= 3 ) { return - 1 ; } let cnt = new Array ( 25 ) ; for ( let i = 0 ; i < 25 ; i ++ ) cnt [ i ] = 0 ; for ( let i = 0 ; i < s . length ; i ++ ) { cnt [ s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; } if ( Math . max ( ... cnt ) >= ( s . length - 1 ) ) { return - 1 ; } else { return ( ans ( s ) ? 1 : 2 ) ; } } let s = " " ; document . write ( solve ( s ) ) ;