2296.设计一个文本编辑器

Posted by 云起 on 2025-02-27
Estimated Reading Time 1 Minutes
Words 191 In Total
Viewed Times

2296.设计一个文本编辑器

地址:2296. 设计一个文本编辑器

思路

双端栈模拟光标左侧和右侧字符串

代码

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
class TextEditor {
public:
vector<char> left;
vector<char> right;
TextEditor() {

}

void addText(string text) {
for (char c : text)
left.push_back(c);
}

int deleteText(int k) {
int cnt = 0;
while (!left.empty() && k > 0)
{
left.pop_back();
k--;
cnt++;
}
return cnt;
}

string cursorLeft(int k) {
int cnt = 0;
while (!left.empty() && k > 0)
{
right.push_back(left.back());
left.pop_back();
k--;
}
int len = left.size();
return string(left.begin() + max(0, len - 10), left.end());
}

string cursorRight(int k) {
int cnt = 0;
while (!right.empty() && k > 0)
{
left.push_back(right.back());
right.pop_back();
k--;
}
int len = left.size();
return string(left.begin() + max(0, len - 10), left.end());
}
};

考虑到返回值序列化,用vector模拟栈


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !