Reduce Hamming distance by swapping two characters | C ++ code to decrease hamming distance using swap . ; Function to return the swapped indexes to get minimum hamming distance . ; Find the initial hamming distance ; Case - I : To decrease distance by two ; ASCII values of present character . ; If two same letters appear in different positions print their indexes ; Store the index of letters which is in wrong position ; Case : II ; If misplaced letter is found , print its original index and its new index ; Store the index of letters in wrong position ; Case - III ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  26 NEW_LINE void Swap ( string s , string t , int n ) { int dp [ MAX ] [ MAX ] ; memset ( dp , -1 , sizeof dp ) ; int tot = 0 ; for ( int i = 0 ; i < n ; i ++ ) if ( s [ i ] != t [ i ] ) tot ++ ; for ( int i = 0 ; i < n ; i ++ ) { int a = s [ i ] - ' a ' ; int b = t [ i ] - ' a ' ; if ( a == b ) continue ; if ( dp [ a ] [ b ] != -1 ) { cout << i + 1 << " ▁ " << dp [ a ] [ b ] + 1 << endl ; return ; } dp [ b ] [ a ] = i ; } int A [ MAX ] , B [ MAX ] ; memset ( A , -1 , sizeof A ) ; memset ( B , -1 , sizeof B ) ; for ( int i = 0 ; i < n ; i ++ ) { int a = s [ i ] - ' a ' ; int b = t [ i ] - ' a ' ; if ( a == b ) continue ; if ( A [ b ] != -1 ) { cout << i + 1 << " ▁ " << A [ b ] + 1 << endl ; return ; } if ( B [ a ] != -1 ) { cout << i + 1 << " ▁ " << B [ a ] + 1 << endl ; return ; } A [ a ] = i ; B [ b ] = i ; } cout << -1 << endl ; } int main ( ) { string S = " permanent " ; string T = " pergament " ; int n = S . length ( ) ; if ( S == " " T == " " ) cout << " Required ▁ string ▁ is ▁ empty . " ; else Swap ( S , T , n ) ; return 0 ; }