Check if a string can be transformed to another by sorting substrings | Function to check if str1 can be transformed to t by sorting substrings ; Occur [ i ] stores the indices of ( ' a ' + i ) in string s ; idx [ i ] stores the next available index of ( ' a ' + i ) in occur [ i ] ; If this is not available anymore ; Conversion not possible ; If one of the smaller characters is available and occurs before ; Conversion not possible ; Print the answer ; Driver Code
def canTransform ( s , t ) : NEW_LINE INDENT n = len ( s ) NEW_LINE occur = [ [ ] for i in range ( 26 ) ] NEW_LINE for x in range ( n ) : NEW_LINE INDENT ch = ord ( s [ x ] ) - ord ( ' a ' ) NEW_LINE occur [ ch ] . append ( x ) NEW_LINE DEDENT idx = [ 0 ] * ( 26 ) NEW_LINE poss = True NEW_LINE for x in range ( n ) : NEW_LINE INDENT ch = ord ( t [ x ] ) - ord ( ' a ' ) NEW_LINE if ( idx [ ch ] >= len ( occur [ ch ] ) ) : NEW_LINE INDENT poss = False NEW_LINE break NEW_LINE DEDENT for small in range ( ch ) : NEW_LINE INDENT if ( idx [ small ] < len ( occur [ small ] ) and occur [ small ] [ idx [ small ] ] < occur [ ch ] [ idx [ ch ] ] ) : NEW_LINE INDENT poss = False NEW_LINE break NEW_LINE DEDENT DEDENT idx [ ch ] += 1 NEW_LINE DEDENT if ( poss ) : NEW_LINE INDENT print ( " Yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " No " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " hdecb " NEW_LINE t = " cdheb " NEW_LINE canTransform ( s , t ) NEW_LINE DEDENT