Check if two strings can be made equal by reversing a substring of one of the strings | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool checkString ( string X , string Y ) { int L = -1 ; int R = -1 ; for ( int i = 0 ; i < X . length ( ) ; ++ i ) { if ( X [ i ] != Y [ i ] ) { L = i ; break ; } } for ( int i = X . length ( ) - 1 ; i > 0 ; -- i ) { if ( X [ i ] != Y [ i ] ) { R = i ; break ; } } reverse ( X . begin ( ) + L , X . begin ( ) + R + 1 ) ; if ( X == Y ) { cout << " Yes " ; } else { cout << " No " ; } } int main ( ) { string X = " adcbef " , Y = " abcdef " ; checkString ( X , Y ) ; return 0 ; }