Skip to the code
cf.
+10 XP

#732 Text Field History

easy

Build undo and redo for a single-line text field. Implement TextHistory:

  • new TextHistory() starts with empty text.
  • type(text) appends text to the current text as one change. Any undone changes can no longer be redone.
  • undo() goes back one change and returns the text; with nothing to undo, it returns the text unchanged.
  • redo() re-applies the most recently undone change and returns the text; with nothing to redo, it returns the text unchanged.
  • getText() returns the current text.

Each example lists the calls in order, then each call's arguments. The first call creates the object with new TextHistory(…); the output lists what each call returns (null for the constructor and for methods that return nothing).

Example 1

Input: ["TextHistory","type","type","undo","undo","redo","getText"]
[[],["Hel"],["lo"],[],[],[],[]]
Output: [null,null,null,"Hel","","Hel","Hel"]

Two changes, two undos back to empty, then one redo brings back Hel.

Example 2

Input: ["TextHistory","type","undo","type","redo","getText"]
[[],["a"],[],["b"],[],[]]
Output: [null,null,"",null,"b","b"]

Typing b after an undo throws away the undone a, so redo has nothing to do.

Constraints

  • Up to 10^4 method calls; typed text is 1 to 20 characters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).