text: Check if a string can be converted to another by swapping of adjacent characters of given type | Java 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: import java . util . * ; class GFG { static boolean canTransform ( String str1 , String str2 ) { String s1 = " " ; String s2 = " " ; for ( char c : str1 . toCharArray ( ) ) { if ( c != ' C ' ) { s1 += c ; } } for ( char c : str2 . toCharArray ( ) ) { if ( c != ' C ' ) { s2 += c ; } } if ( ! s1 . equals ( s2 ) ) return false ; int i = 0 ; int j = 0 ; int n = str1 . length ( ) ; while ( i < n && j < n ) { if ( str1 . charAt ( i ) == ' C ' ) { i ++ ; } else if ( str2 . charAt ( j ) == ' C ' ) { j ++ ; } else { if ( ( str1 . charAt ( i ) == ' A ' && i < j ) || ( str1 . charAt ( i ) == ' B ' && i > j ) ) { return false ; } i ++ ; j ++ ; } } return true ; } public static void main ( String [ ] args ) { String str1 = " BCCABCBCA " ; String str2 = " CBACCBBAC " ; if ( canTransform ( str1 , str2 ) ) { System . out . print ( " Yes " ) ; } else { System . out . print ( " No " ) ; } } }