Lexicographically smallest string whose hamming distance from given string is exactly K | function to find Lexicographically smallest string with hamming distance k ; If k is 0 , output input string ; Copying input string into output string ; Traverse all the character of the string ; If current character is not ' a ' ; copy character ' a ' to output string ; str2 [ i ] = ' a ' ; ; If hamming distance became k , break ; ; If k is less than p ; Traversing string in reverse order ; Driver Code
< ? php function findString ( $ str , $ n , $ k ) { if ( $ k == 0 ) { echo $ str . " STRNEWLINE " ; return ; } $ str2 = $ str ; $ p = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ str2 [ $ i ] != ' a ' ) { $ str2 [ $ i ] = ' a ' ; $ p ++ ; p ++ ; if ( $ p == $ k ) break ; } } if ( $ p < $ k ) { for ( $ i = $ n - 1 ; $ i >= 0 ; $ i -- ) if ( $ str [ $ i ] == ' a ' ) { $ str2 [ $ i ] = ' b ' ; $ p ++ ; if ( $ p == $ k ) break ; } } echo $ str2 . " STRNEWLINE " ; } $ str = " pqrs " ; $ n = strlen ( $ str ) ; $ k = 2 ; findString ( $ str , $ n , $ k ) ; ? >