text: Check if a string can be converted to another by swapping of adjacent characters of given type | C ++ program for the above approach ; Function to check if it is possible to transform start to end ; Check the sequence of A , B in both strings str1 and str2 ; If both the strings are not equal ; Traverse the strings ; Check for indexes of A and B ; Driver Code ; Function Call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool canTransform ( string str1 , string str2 ) { string s1 = " " ; string s2 = " " ; for ( char c : str1 ) { if ( c != ' C ' ) { s1 += c ; } } for ( char c : str2 ) { if ( c != ' C ' ) { s2 += c ; } } if ( s1 != s2 ) return false ; int i = 0 ; int j = 0 ; int n = str1 . length ( ) ; while ( i < n and j < n ) { if ( str1 [ i ] == ' C ' ) { i ++ ; } else if ( str2 [ j ] == ' C ' ) { j ++ ; } else { if ( ( str1 [ i ] == ' A ' and i < j ) or ( str1 [ i ] == ' B ' and i > j ) ) { return false ; } i ++ ; j ++ ; } } return true ; } int main ( ) { string str1 = " BCCABCBCA " ; string str2 = " CBACCBBAC " ; if ( canTransform ( str1 , str2 ) ) { cout << " Yes " ; } else { cout << " No " ; } return 0 ; }