Skip to content

Commit 2e68c4d

Browse files
committed
Addition to Linked List Leetcode Problems
Added Design A Text Editor Problem. Leetcode-2296
1 parent e8f8fc3 commit 2e68c4d

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
class TextEditor
4+
{
5+
private:
6+
list<char> a;
7+
// If delete, will delete position cur - 1, not position cur.
8+
list<char>::iterator cur;
9+
10+
public:
11+
TextEditor()
12+
{
13+
a.clear();
14+
// For convenience.
15+
a.push_back('A');
16+
cur = a.end();
17+
}
18+
19+
void addText(string text)
20+
{
21+
a.insert(cur, text.begin(), text.end());
22+
}
23+
24+
int deleteText(int k)
25+
{
26+
int cnt = 0;
27+
// Move to the position that will be deleted.
28+
cur--;
29+
while (k--)
30+
{
31+
if (cur == a.begin())
32+
break;
33+
cnt++;
34+
a.erase(cur--);
35+
}
36+
// Adjust the position of the cursor.
37+
cur++;
38+
return cnt;
39+
}
40+
41+
// Left 10 chars.
42+
string solve()
43+
{
44+
auto tt = cur;
45+
tt--;
46+
string ret;
47+
int k = 10;
48+
while (k--)
49+
{
50+
if (tt == a.begin())
51+
break;
52+
ret += (*(tt--));
53+
}
54+
reverse(ret.begin(), ret.end());
55+
return ret;
56+
}
57+
58+
string cursorLeft(int k)
59+
{
60+
while (k--)
61+
{
62+
auto nxt = cur;
63+
nxt--;
64+
// Never move the cursor to the first position.
65+
if (nxt == a.begin())
66+
break;
67+
cur = nxt;
68+
}
69+
return solve();
70+
}
71+
72+
string cursorRight(int k)
73+
{
74+
while (k--)
75+
{
76+
if (cur == a.end())
77+
break;
78+
cur++;
79+
}
80+
return solve();
81+
}
82+
};

0 commit comments

Comments
 (0)