Check if two strings can be made equal by reversing a substring of one of the strings | Function to check if the Strings can be made equal or not by reversing a subString of X ; Store the first index from the left which contains unequal characters in both the Strings ; Store the first element from the right which contains unequal characters in both the Strings ; Checks for the first index from left in which characters in both the Strings are unequal ; Store the current index ; Break out of the loop ; Checks for the first index from right in which characters in both the Strings are unequal ; Store the current index ; Break out of the loop ; Reverse the subString X [ L , R ] ; If X and Y are equal ; Otherwise ; Driver Code ; Function Call
function checkString ( X , Y ) { var L = - 1 ; var R = - 1 ; for ( var i = 0 ; i < X . length ; ++ i ) { if ( X [ i ] !== Y [ i ] ) { L = i ; break ; } } for ( var i = X . length - 1 ; i > 0 ; -- i ) { if ( X [ i ] !== Y [ i ] ) { R = i ; break ; } } X = X . substring ( 0 , L ) + reverse ( X . substring ( L , R + 1 ) ) + X . substring ( R + 1 ) ; if ( X === Y ) { document . write ( " " ) ; } else { document . write ( " " ) ; } } function reverse ( input ) { var a = input . split ( " " ) ; var l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { var temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return a . join ( " " ) ; } var X = " " , Y = " " ; checkString ( X , Y ) ;