Convert given string to another by minimum replacements of subsequences by its smallest character | C # program for the above approach ; Function to return the minimum number of operation ; Storing data ; Initialize both arrays ; Stores the index of character ; Filling str1array , convChar and hashmap convertMap . ; Not possible to convert ; Calculate result Initializing return values ; Iterating the character from the end ; Increment the number of operations ; Not possible to convert ; To check whether the final element has been added in set S or not . ; Check if v1 [ j ] is present in hashmap or not ; Already converted then then continue ; Not possible to convert ; Print the result ; Driver code ; Given strings ; Function call
using System ; using System . Collections . Generic ; class GFG { static void transformString ( string str1 , string str2 ) { int N = str1 . Length ; List < List < int > > convChar = new List < List < int > > ( ) ; List < List < int > > str1array = new List < List < int > > ( ) ; for ( int i = 0 ; i < 26 ; i ++ ) { convChar . Add ( new List < int > ( ) ) ; str1array . Add ( new List < int > ( ) ) ; } Dictionary < int , char > convertMap = new Dictionary < int , char > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { str1array [ str1 [ i ] - ' a ' ] . Add ( i ) ; } for ( int i = 0 ; i < N ; i ++ ) { if ( str1 [ i ] < str2 [ i ] ) { Console . WriteLine ( - 1 ) ; return ; } else if ( str1 [ i ] == str2 [ i ] ) continue ; else { convChar [ str2 [ i ] - ' a ' ] . Add ( i ) ; convertMap [ i ] = str2 [ i ] ; } } int ret = 0 ; List < List < int > > retv = new List < List < int > > ( ) ; for ( int i = 25 ; i >= 0 ; i -- ) { List < int > v = convChar [ i ] ; if ( v . Count == 0 ) continue ; ret ++ ; List < int > v1 = str1array [ i ] ; if ( v1 . Count == 0 ) { Console . WriteLine ( - 1 ) ; return ; } bool isScompleted = false ; for ( int j = 0 ; j < v1 . Count ; j ++ ) { if ( convertMap . ContainsKey ( v1 [ j ] ) ) { char a = convertMap [ v1 [ j ] ] ; if ( a > i + ' a ' ) continue ; else { v . Add ( v1 [ j ] ) ; isScompleted = true ; retv . Add ( v ) ; break ; } } else { v . Add ( v1 [ j ] ) ; isScompleted = true ; retv . Add ( v ) ; break ; } } if ( ! isScompleted ) { Console . WriteLine ( - 1 ) ; return ; } } Console . WriteLine ( ret ) ; } static void Main ( ) { string A = " abcab " ; string B = " aabab " ; transformString ( A , B ) ; } }