Minimum cost to convert str1 to str2 with the given operations | C ++ implementation of the approach ; Function to return the minimum cost to convert str1 to sr2 ; For every character of str1 ; If current character is not equal in both the strings ; If the next character is also different in both the strings then these characters can be swapped ; Change the current character ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( string str1 , string str2 , int n ) { int cost = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( str1 [ i ] != str2 [ i ] ) { if ( i < n - 1 && str1 [ i + 1 ] != str2 [ i + 1 ] ) { swap ( str1 [ i ] , str1 [ i + 1 ] ) ; cost ++ ; } else { cost ++ ; } } } return cost ; } int main ( ) { string str1 = " abb " , str2 = " bba " ; int n = str1 . length ( ) ; cout << minCost ( str1 , str2 , n ) ; return 0 ; }