-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
design-a-text-editor.cpp
52 lines (43 loc) · 1.1 KB
/
design-a-text-editor.cpp
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
// Time: ctor: O(1)
// addText: O(l)
// deleteText: O(k)
// cursorLeft: O(k)
// cursorRight: O(k)
// Space: O(n)
// design, stack
class TextEditor {
public:
TextEditor() {
}
void addText(string text) {
left_ += text;
}
int deleteText(int k) {
return move(k, &left_, nullptr);
}
string cursorLeft(int k) {
move(k, &left_, &right_);
return last_characters();
}
string cursorRight(int k) {
move(k, &right_, &left_);
return last_characters();
}
private:
int move(const int k, string *src, string *dst) {
const int cnt = min(k, static_cast<int>(size(*src)));
for (int _ = 0; _ < cnt; ++_) {
if (dst) {
dst->push_back(src->back());
}
src->pop_back();
}
return cnt;
}
string last_characters() {
return left_.substr(max(static_cast<int>(size(left_)) - LAST_COUNT, 0), LAST_COUNT);
}
static const int LAST_COUNT = 10;
string left_;
string right_;
};