Palindrome by swapping only one character | Java program palindrome by swapping only one character ; convert the string to character array ; counts the number of differences which prevents the string from being palindrome . ; keeps a record of the characters that prevents the string from being palindrome . ; loops from the start of a string till the midpoint of the string ; difference is encountered preventing the string from being palindrome ; 3 rd differences encountered and its no longer possible to make is palindrome by one swap ; record the different character ; store the different characters ; its already palindrome ; only one difference is found ; if the middleChar matches either of the difference producing characters , return true ; two differences are found ; if the characters contained in the two sets are same , return true ; Driver code
class GFG { public static boolean isPalindromePossible ( String input ) { int len = input . length ( ) , i ; char [ ] charStr = input . toCharArray ( ) ; int diffCount = 0 ; char [ ] [ ] diff = new char [ 2 ] [ 2 ] ; for ( i = 0 ; i < len / 2 ; i ++ ) { if ( charStr [ i ] != charStr [ len - i - 1 ] ) { if ( diffCount == 2 ) return false ; diff [ diffCount ] [ 0 ] = charStr [ i ] ; diff [ diffCount ++ ] [ 1 ] = charStr [ len - i - 1 ] ; } } switch ( diffCount ) { case 0 : return true ; case 1 : char midChar = charStr [ i ] ; if ( len % 2 != 0 && ( diff [ 0 ] [ 0 ] == midChar diff [ 0 ] [ 1 ] == midChar ) ) return true ; case 2 : if ( ( diff [ 0 ] [ 0 ] == diff [ 1 ] [ 0 ] && diff [ 0 ] [ 1 ] == diff [ 1 ] [ 1 ] ) || ( diff [ 0 ] [ 0 ] == diff [ 1 ] [ 1 ] && diff [ 0 ] [ 1 ] == diff [ 1 ] [ 0 ] ) ) return true ; } return false ; } public static void main ( String [ ] args ) { System . out . println ( isPalindromePossible ( " bbg " ) ) ; System . out . println ( isPalindromePossible ( " bdababd " ) ) ; System . out . println ( isPalindromePossible ( " gcagac " ) ) ; } }