Text Editor
NetflixOnsiteMedium
You design a text editor that keeps its document as a single string. The document starts empty, and every edit happens at the end of the text: append adds characters there and delete removes characters from there. Each test creates one Editor instance and runs a sequence of method calls, recording every call's return value (None for methods that return nothing).
Part 1: Append, delete and undo
Implement a class Editor with these methods:
append(s)adds the stringsto the end of the text. ReturnsNone.delete(k)removes the lastkcharacters, or the whole text when it has fewer thankcharacters. Returns the number of characters actually removed.undo()reverts the most recent edit that has not been undone yet and returnsTrue, or returnsFalsewhen there is no such edit. Repeatedundo()calls walk back through the history one edit at a time.text()returns the current text.
An edit is an append, or a delete that removed at least one character. A delete that removes nothing is not an edit: it is not recorded, so undo() never reverts it.
- Example 1
- init
[]- operations
[["append",["hello"]],["append",[" world"]],["text",[]],["delete",[3]],["text",[]],["undo",[]],["text",[]],["undo",[]],["text",[]],["undo",[]],["text",[]],["undo",[]],["undo",[]]]- Output
[null,null,"hello world",3,"hello wo",true,"hello world",true,"hello",true,"",false,false]
Why:
delete(3)trims the text tohello wo. Eachundo()reverts one edit in reverse order: the delete, then the append ofworld, then the append ofhello. The last twoundo()calls find no un-reverted edit and returnFalse.
Constraints
1 <= len(operations) <= 10^41 <= len(s) <= 1001 <= k <= 10^4- each character of
ssatisfies'a' <= s[i] <= 'z'