Palindrome by swapping only one character | Python3 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
def isPalindromePossible ( input : str ) -> bool : NEW_LINE INDENT length = len ( input ) NEW_LINE diffCount = 0 NEW_LINE i = 0 NEW_LINE diff = [ [ '0' ] * 2 ] * 2 NEW_LINE while i < length // 2 : NEW_LINE INDENT if input [ i ] != input [ length - i - 1 ] : NEW_LINE INDENT if diffCount == 2 : NEW_LINE INDENT return False NEW_LINE DEDENT diff [ diffCount ] [ 0 ] = input [ i ] NEW_LINE diff [ diffCount ] [ 1 ] = input [ length - i - 1 ] NEW_LINE diffCount += 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT if diffCount == 0 : NEW_LINE INDENT return True NEW_LINE DEDENT elif diffCount == 1 : NEW_LINE INDENT midChar = input [ i ] NEW_LINE if length % 2 != 0 and ( diff [ 0 ] [ 0 ] == midChar or diff [ 0 ] [ 1 ] == midChar ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT elif diffCount == 2 : NEW_LINE INDENT 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 ] ) : NEW_LINE INDENT return True NEW_LINE DEDENT DEDENT return False NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT print ( isPalindromePossible ( " bbg " ) ) NEW_LINE print ( isPalindromePossible ( " bdababd " ) ) NEW_LINE print ( isPalindromePossible ( " gcagac " ) ) NEW_LINE DEDENT