Design a class Editor for a single line of text with unlimited undo and redo.
Editor(): start with empty text.type(s): append the stringsto the text.erase(k): remove the lastkcharacters (all of them if fewer thankexist).undo(): revert the most recenttypeorerasethat has not been undone, then return the text. If there is nothing to undo, return the text unchanged.redo(): re-apply the most recently undone edit, then return the text. If there is nothing to redo, return the text unchanged.text(): return the current text.
Performing a new type or erase clears the redo history. Every type and erase call counts as an edit, even one that changes nothing (such as erase(0)), so it is also what the next undo reverts.
Examples
Input: ops = ["Editor", "type", "type", "text", "undo", "redo", "erase", "undo", "type", "redo", "undo", "undo", "undo"]
args = [[], ["hel"], ["lo"], [], [], [], [2], [], ["!"], [], [], [], []]
Output: [None, None, None, "hello", "hel", "hello", None, "hello", None, "hello!", "hello", "hel", ""]
Explanation: after type("!") the erased state can no longer be redone; the three undos walk all the way back to empty text.
Constraints
- At most
2000operations; the text never exceeds5000characters - Target:
O(len(text))per operation is acceptable
Goals
- Save previous states on an undo stack and undone states on a redo stack
- Discard the redo stack whenever a fresh edit happens