Minimum number of flips or swaps of adjacent characters required to make two strings equal | Java program for the above approach ; Function to count the minimum number of operations required to make strings A and B equal ; Stores all dp - states ; Update the value of A [ i ] ; Iterate over the range [ 1 , N ] ; If A [ i - 1 ] equals to B [ i - 1 ] ; Assign Dp [ i - 1 ] to Dp [ i ] ; Otherwise ; Update dp [ i ] ; If swapping is possible ; Update dp [ i ] ; Return the minimum number of steps required ; Driver code ; Given Input ; Function Call
import java . io . * ; class GFG { static int countMinSteps ( String A , String B , int N ) { int [ ] dp = new int [ N + 1 ] ; for ( int i = 1 ; i <= N ; i ++ ) { dp [ i ] = 0 ; } for ( int i = 1 ; i <= N ; i ++ ) { if ( A . charAt ( i - 1 ) == B . charAt ( i - 1 ) ) { dp [ i ] = dp [ i - 1 ] ; } else { dp [ i ] = dp [ i - 1 ] + 1 ; } if ( i >= 2 && A . charAt ( i - 2 ) == B . charAt ( i - 1 ) && A . charAt ( i - 1 ) == B . charAt ( i - 2 ) ) { dp [ i ] = Math . min ( dp [ i ] , dp [ i - 2 ] + 1 ) ; } } return dp [ N ] ; } public static void main ( String [ ] args ) { String A = "0101" ; String B = "0011" ; int N = A . length ( ) ; System . out . println ( countMinSteps ( A , B , N ) ) ; } }