Replace two substrings ( of a string ) with each other | Function to return the resultant string ; Iterate through all positions i ; Current sub - string of length = len ( A ) = len ( B ) ; If current sub - string gets equal to A or B ; Update S after replacing A ; Update S after replacing B ; Return the updated string ; Driver code
def updateString ( S , A , B ) : NEW_LINE INDENT l = len ( A ) NEW_LINE i = 0 NEW_LINE while i + l <= len ( S ) : NEW_LINE INDENT curr = S [ i : i + l ] NEW_LINE if curr == A : NEW_LINE INDENT new_string = S [ 0 : i ] + B + S [ i + l : len ( S ) ] NEW_LINE S = new_string NEW_LINE i += l - 1 NEW_LINE DEDENT else : NEW_LINE INDENT new_string = S [ 0 : i ] + A + S [ i + l : len ( S ) ] NEW_LINE S = new_string NEW_LINE i += l - 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return S NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " aab " NEW_LINE A = " aa " NEW_LINE B = " bb " NEW_LINE print ( updateString ( S , A , B ) ) NEW_LINE DEDENT