Palindrome by swapping only one character | C ++ program palindrome by swapping only one character ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPalindromePossible ( string input ) { int len = input . length ( ) ; int diffCount = 0 , i ; char diff [ 2 ] [ 2 ] ; for ( i = 0 ; i < len / 2 ; i ++ ) { if ( input [ i ] != input [ len - i - 1 ] ) { if ( diffCount == 2 ) return false ; diff [ diffCount ] [ 0 ] = input [ i ] ; diff [ diffCount ++ ] [ 1 ] = input [ len - i - 1 ] ; } } switch ( diffCount ) { case 0 : return true ; case 1 : { char midChar = input [ i ] ; if ( len % 2 != 0 and ( diff [ 0 ] [ 0 ] == midChar or diff [ 0 ] [ 1 ] == midChar ) ) return true ; } case 2 : if ( ( diff [ 0 ] [ 0 ] == diff [ 1 ] [ 0 ] and diff [ 0 ] [ 1 ] == diff [ 1 ] [ 1 ] ) or ( diff [ 0 ] [ 0 ] == diff [ 1 ] [ 1 ] and diff [ 0 ] [ 1 ] == diff [ 1 ] [ 0 ] ) ) return true ; } return false ; } int main ( ) { cout << boolalpha << isPalindromePossible ( " bbg " ) << endl ; cout << boolalpha << isPalindromePossible ( " bdababd " ) << endl ; cout << boolalpha << isPalindromePossible ( " gcagac " ) << endl ; return 0 ; }