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
using System ; class GFG { static readonly int MAX = 26 ; static void Swap ( string s , string t , int n ) { int [ , ] dp = new int [ MAX , MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) { for ( int j = 0 ; j < MAX ; j ++ ) { dp [ i , j ] = - 1 ; } } 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 ) { Console . WriteLine ( i + 1 + " ▁ " + ( dp [ a , b ] + 1 ) ) ; return ; } dp [ b , a ] = i ; } int [ ] A = new int [ MAX ] ; int [ ] B = new int [ MAX ] ; for ( int i = 0 ; i < MAX ; i ++ ) { A [ i ] = - 1 ; B [ i ] = - 1 ; } 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 ) { Console . WriteLine ( i + 1 + " ▁ " + ( A [ b ] + 1 ) ) ; return ; } if ( B [ a ] != - 1 ) { Console . WriteLine ( i + 1 + " ▁ " + ( B [ a ] + 1 ) ) ; return ; } A [ a ] = i ; B [ b ] = i ; } Console . WriteLine ( - 1 ) ; } public static int Main ( ) { string S = " permanent " ; string T = " pergament " ; int n = S . Length ; if ( S == " " T == " " ) Console . WriteLine ( " Required ▁ string ▁ is ▁ empty . " ) ; else Swap ( S , T , n ) ; return 0 ; } }