Count characters to be shifted from the start or end of a string to obtain another string | C ++ 14 program for the above approach ; Function to find the minimum cost to convert string A to string B ; Length of string ; Initialize maxlen as 0 ; Traverse the string A ; Stores the length of substrings of string A ; Traversing string B for each character of A ; Shift i pointer towards right and increment length , if A [ i ] equals B [ j ] ; If traverse till end ; Update maxlen ; Return minimum cost ; Driver Code ; Given two strings A and B ; Function call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minCost ( string A , string B ) { int n = A . size ( ) ; int i = 0 ; int maxlen = 0 ; while ( i < n ) { int length = 0 ; for ( int j = 0 ; j < n ; ++ j ) { if ( A [ i ] == B [ j ] ) { ++ i ; ++ length ; if ( i == n ) break ; } } maxlen = max ( maxlen , length ) ; } return n - maxlen ; } int main ( ) { string A = " edacb " ; string B = " abcde " ; cout << minCost ( A , B ) << endl ; }