Design a Text Editor LeetCode solution in C++

1
class TextEditor {
2
stack<char> left;
3
stack<char> right;
4

5
public:
6
TextEditor() {}
7

8
void addText(string text) {
9
for (auto &c : text) {
10
left.push(c);
11
}
12
}
13

14
int deleteText(int k) {
15
int cnt = 0;
16
while (!left.empty() and k > 0) {
17
left.pop();
18
cnt++;
19
k--;
20
}
21
return cnt;
22
}
23

24
string cursorLeft(int k) {
25
while (!left.empty() and k > 0) {
26
char c = left.top();
27
left.pop();
28
right.push(c);
29
k--;
30
}
31
// returning the last min(10, len) characters to the left of the cursor
32
return cursorShiftString();
33
}
34

35
string cursorRight(int k) {
36
while (!right.empty() and k > 0) {
37
char c = right.top();
38
right.pop();
39
left.push(c);
40
k--;
41
}
42
// returning the last min(10, len) characters to the left of the cursor
43
return cursorShiftString();
44
}
45

46
// function to return the last min(10, len) characters to the left of the
47
// cursor
48
string cursorShiftString() {
49
string rtn = "";
50
int cnt = 10;
51
while (!left.empty() and cnt > 0) {
52
char c = left.top();
53
left.pop();
54
rtn += c;
55
cnt--;
56
}
57
reverse(rtn.begin(), rtn.end());
58
for (int i = 0; i < rtn.size(); i++) {
59
left.push(rtn[i]);
60
}
61
return rtn;
62
}
63
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0