Text Editor with Undo
FigmaPhone screenMedium
You will build a class TextEditor that holds a piece of text, initially empty. Positions are zero-based indexes into the text.
An edit op is a list of one of these forms:
["insert", index, text]insertstextatindex["delete", start, end]removes the characters fromstartup to but not includingend["replace", start, end, text]replaces that range withtext
Each test drives one TextEditor instance through a sequence of calls.
Part 1: Apply and undo
Implement apply(op), get_text() and undo().
apply applies one edit to the text. get_text returns the current text. undo reverts the most recent applied edit that has not been undone, restoring the text exactly as it was before that edit; if there is nothing to revert, it does nothing.
Each call to apply is one undoable step. apply and undo return None.
- Example 1
- init
[]- operations
[["apply",[["insert",0,"hello"]]],["get_text",[]],["apply",[["insert",5," world"]]],["get_text",[]],["undo",[]],["get_text",[]],["apply",[["replace",0,5,"bye"]]],["get_text",[]],["undo",[]],["get_text",[]],["undo",[]],["get_text",[]],["undo",[]],["get_text",[]]]- Output
[null,"hello",null,"hello world",null,"hello",null,"bye",null,"hello",null,"",null,""]
Why: The first undo removes
world. Undoing thereplacerestores all five letters ofhello; the next undo removes it, and the last undo has nothing left to revert, so the text stays empty.
Constraints
0 <= len(operations) <= 10^40 <= index <= len(text)at the time of eachinsert0 <= start <= end <= len(text)at the time of eachdeleteorreplace- The text never exceeds
10^5characters