Minimum number of flips or swaps of adjacent characters required to make two strings equal | C ++ 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 ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMinSteps ( string A , string B , int N ) { vector < int > dp ( N + 1 , 0 ) ; for ( int i = 1 ; i <= N ; i ++ ) { if ( A [ i - 1 ] == B [ i - 1 ] ) { dp [ i ] = dp [ i - 1 ] ; } else { dp [ i ] = dp [ i - 1 ] + 1 ; } if ( i >= 2 && A [ i - 2 ] == B [ i - 1 ] && A [ i - 1 ] == B [ i - 2 ] ) { dp [ i ] = min ( dp [ i ] , dp [ i - 2 ] + 1 ) ; } } return dp [ N ] ; } int main ( ) { string A = "0101" ; string B = "0011" ; int N = A . length ( ) ; cout << countMinSteps ( A , B , N ) ; return 0 ; }