Reduce Hamming distance by swapping two characters | Java 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
import java . util . Arrays ; class GFG { static final 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 . charAt ( i ) != t . charAt ( i ) ) tot ++ ; for ( int i = 0 ; i < n ; i ++ ) { int a = s . charAt ( i ) - ' a ' ; int b = t . charAt ( i ) - ' a ' ; if ( a == b ) continue ; if ( dp [ a ] [ b ] != - 1 ) { System . out . println ( i + 1 + " ▁ " + ( dp [ a ] [ b ] + 1 ) ) ; return ; } dp [ b ] [ a ] = i ; } int A [ ] = new int [ MAX ] , B [ ] = new int [ MAX ] ; Arrays . fill ( A , - 1 ) ; Arrays . fill ( B , - 1 ) ; for ( int i = 0 ; i < n ; i ++ ) { int a = s . charAt ( i ) - ' a ' ; int b = t . charAt ( i ) - ' a ' ; if ( a == b ) continue ; if ( A [ b ] != - 1 ) { System . out . println ( i + 1 + " ▁ " + ( A [ b ] + 1 ) ) ; return ; } if ( B [ a ] != - 1 ) { System . out . println ( i + 1 + " ▁ " + ( B [ a ] + 1 ) ) ; return ; } A [ a ] = i ; B [ b ] = i ; } System . out . println ( - 1 ) ; } public static void main ( String [ ] args ) { String S = " permanent " ; String T = " pergament " ; int n = S . length ( ) ; if ( S == " " T == " " ) System . out . println ( " Required ▁ string ▁ is ▁ empty . " ) ; else Swap ( S , T , n ) ; } }