Check if two strings can be made equal by reversing a substring of one of the strings | Java program for the above approach ; 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
import java . util . * ; class GFG { static void checkString ( String X , String Y ) { int L = - 1 ; int R = - 1 ; for ( int i = 0 ; i < X . length ( ) ; ++ i ) { if ( X . charAt ( i ) != Y . charAt ( i ) ) { L = i ; break ; } } for ( int i = X . length ( ) - 1 ; i > 0 ; -- i ) { if ( X . charAt ( i ) != Y . charAt ( i ) ) { R = i ; break ; } } X = X . substring ( 0 , L ) + reverse ( X . substring ( L , R + 1 ) ) + X . substring ( R + 1 ) ; if ( X . equals ( Y ) ) { System . out . print ( " Yes " ) ; } else { System . out . print ( " No " ) ; } } static String reverse ( String input ) { char [ ] a = input . toCharArray ( ) ; int l , r = a . length - 1 ; for ( l = 0 ; l < r ; l ++ , r -- ) { char temp = a [ l ] ; a [ l ] = a [ r ] ; a [ r ] = temp ; } return String . valueOf ( a ) ; } public static void main ( String [ ] args ) { String X = " adcbef " , Y = " abcdef " ; checkString ( X , Y ) ; } }