[LeetCode] Design a Text Editor

2296. Design a Text Editor

Design a text editor with a cursor that can do the following:

  • Add text to where the cursor is.
  • Delete text from where the cursor is (simulating the backspace key).
  • Move the cursor either left or right.

When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds.

Implement the TextEditor class:

  • TextEditor() Initializes the object with empty text.
  • void addText(string text) Appends text to where the cursor is. The cursor ends to the right of text.
  • int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number of characters actually deleted.
  • string cursorLeft(int k) Moves the cursor to the left k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
  • string cursorRight(int k) Moves the cursor to the right k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class TextEditor {
list<char> l;
list<char>::iterator c = l.begin();
string print() {
if(c == begin(l)) return "";

string res = "";
for(auto it = prev(c); it != begin(l) and res.length() < 10; it--) {
res.push_back(*it);
}
if(res.length() < 10) res.push_back(*begin(l));
reverse(begin(res), end(res));
return res;
}
public:
TextEditor() {}

void addText(string text) {
for(auto& ch : text) {
c = l.insert(c, ch);
c = next(c);
}
}

int deleteText(int k) {
if(c == begin(l)) return 0;

int res = 0;

while(c != begin(l) and k--) {
res++;
l.erase(prev(c));
}

return res;
}

string cursorLeft(int k) {
while(k-- and c != begin(l)) {
c = prev(c);
}

return print();
}

string cursorRight(int k) {
while(k-- and c != end(l)) {
c = next(c);
}

return print();
}
};

/**
* Your TextEditor object will be instantiated and called as such:
* TextEditor* obj = new TextEditor();
* obj->addText(text);
* int param_2 = obj->deleteText(k);
* string param_3 = obj->cursorLeft(k);
* string param_4 = obj->cursorRight(k);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/05/PS/LeetCode/design-a-text-editor/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.