Problem 285948 · medium · Level 02 Linear Data Structures

Editor With Undo and Redo

stacks · class design · simulation

Design a class Editor for a single line of text with unlimited undo and redo.

  • Editor(): start with empty text.
  • type(s): append the string s to the text.
  • erase(k): remove the last k characters (all of them if fewer than k exist).
  • undo(): revert the most recent type or erase that 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.

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 2000 operations; the text never exceeds 5000 characters
  • 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
Starting Python…