#2296

Design a Text Editor

candidate master · 1455 · lc hard +32 · 50.1% accepted · 654 likes · top 38%

Description

Design a text editor with a cursor that can:

- Insert text at the current cursor position.

- Delete characters immediately to the left of the cursor.

- Move the cursor left or right.

The cursor stays within the text at all times: 0 <= cursor.position <= currentText.length.

Implement the TextEditor class:

- TextEditor() Creates an editor with empty text.

- void addText(string text) Inserts text at the cursor; cursor ends up to the right of the inserted text.

- int deleteText(int k) Deletes up to k characters to the left; returns the actual number deleted.

- string cursorLeft(int k) Moves cursor left up to k steps; returns up to 10 characters immediately left of the cursor.

- string cursorRight(int k) Moves cursor right up to k steps; returns up to 10 characters immediately left of the cursor.

Example 1:

Input
["TextEditor", "addText", "deleteText", "addText", "cursorRight", "cursorLeft", "deleteText", "cursorLeft", "cursorRight"]
[[], ["leetcode"], [4], ["practice"], [3], [8], [10], [2], [6]]
Output
[null, null, 4, null, "etpractice", "leet", 4, "", "practi"]

Example 2:

Explanation
TextEditor textEditor = new TextEditor(); // The current text is "|". (The '|' character represents the cursor)
textEditor.addText("leetcode"); // The current text is "leetcode|".
textEditor.deleteText(4); // return 4
// The current text is "leet|".
// 4 characters were deleted.
textEditor.addText("practice"); // The current text is "leetpractice|".
textEditor.cursorRight(3); // return "etpractice"
// The current text is "leetpractice|".
// The cursor cannot be moved beyond the actual text and thus did not move.
// "etpractice" is the last 10 characters to the left of the cursor.
textEditor.cursorLeft(8); // return "leet"
// The current text is "leet|practice".
// "leet" is the last min(10, 4) = 4 characters to the left of the cursor.
textEditor.deleteText(10); // return 4
// The current text is "|practice".
// Only 4 characters were deleted.
textEditor.cursorLeft(2); // return ""
// The current text is "|practice".
// The cursor cannot be moved beyond the actual text and thus did not move.
// "" is the last min(10, 0) = 0 characters to the left of the cursor.
textEditor.cursorRight(6); // return "practi"
// The current text is "practi|ce".
// "practi" is the last min(10, 6) = 6 characters to the left of the cursor.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24