Find the resultant String after replacing X with Y and removing Z | Function to replace and remove ; Two pointer start and end points to beginning and end position in the string ; If start is having Z find X pos in end and replace Z with another character ; Find location for having different character instead of Z ; If found swap character at start and end ; Else increment start Also checkin for X at start position ; Driver code
def replaceRemove ( s , X , Y , Z ) : NEW_LINE INDENT s = list ( s ) ; NEW_LINE start = 0 ; NEW_LINE end = len ( s ) - 1 ; NEW_LINE while ( start <= end ) : NEW_LINE INDENT if ( s [ start ] == Z ) : NEW_LINE INDENT while ( end >= 0 and s [ end ] == Z ) : NEW_LINE INDENT end -= 1 ; NEW_LINE DEDENT if ( end > start ) : NEW_LINE INDENT s [ start ] , s [ end ] = s [ end ] , s [ start ] NEW_LINE if ( s [ start ] == X ) : NEW_LINE INDENT s [ start ] = Y ; NEW_LINE DEDENT start += 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT if ( s [ start ] == X ) : NEW_LINE INDENT s [ start ] = Y ; NEW_LINE DEDENT start += 1 ; NEW_LINE DEDENT DEDENT while ( len ( s ) > 0 and s [ len ( s ) - 1 ] == Z ) : NEW_LINE INDENT s . pop ( ) ; NEW_LINE DEDENT return " " . join ( s ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " batman " ; NEW_LINE X = ' a ' ; Y = ' d ' ; Z = ' b ' ; NEW_LINE string = replaceRemove ( string , X , Y , Z ) ; NEW_LINE if ( len ( string ) == 0 ) : NEW_LINE INDENT print ( - 1 ) ; NEW_LINE DEDENT else : NEW_LINE INDENT print ( string ) ; NEW_LINE DEDENT DEDENT