Convert a Binary String to another by flipping prefixes minimum number of times | Java program for the above approach ; Function to count minimum number of operations required to convert string a to another string b ; Store the lengths of each prefixes selected ; Traverse the string ; If first character is same as b [ i ] ; Insert 1 to ops [ ] ; And , flip the bit ; Reverse the prefix string of length i + 1 ; Flip the characters in this prefix length ; Push ( i + 1 ) to array ops [ ] ; Print the number of operations ; Print the length of each prefixes stored ; Function to reverse a [ ] from start to end ; Driver code
import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void minOperations ( String s1 , String s2 , int n ) { char a [ ] = s1 . toCharArray ( ) ; char b [ ] = s2 . toCharArray ( ) ; ArrayList < Integer > ops = new ArrayList < > ( ) ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( a [ i ] != b [ i ] ) { if ( a [ 0 ] == b [ i ] ) { ops . add ( 1 ) ; a [ 0 ] = ( a [ 0 ] == '0' ? '1' : '0' ) ; } reverse ( a , 0 , i ) ; for ( int j = 0 ; j <= i ; j ++ ) { a [ j ] = ( a [ j ] == '0' ? '1' : '0' ) ; } ops . add ( i + 1 ) ; } } System . out . println ( ops . size ( ) ) ; for ( int x : ops ) { System . out . print ( x + " ▁ " ) ; } } static void reverse ( char a [ ] , int start , int end ) { while ( start < end ) { char temp = a [ start ] ; a [ start ] = a [ end ] ; a [ end ] = temp ; start ++ ; end -- ; } } public static void main ( String [ ] args ) { String a = "10" , b = "01" ; int N = a . length ( ) ; minOperations ( a , b , N ) ; } }