forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
design-a-text-editor.py
56 lines (48 loc) · 1.24 KB
/
design-a-text-editor.py
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
# Time: ctor: O(1)
# addText: O(l)
# deleteText: O(k)
# cursorLeft: O(k)
# cursorRight: O(k)
# Space: O(n)
# design, stack
class TextEditor(object):
def __init__(self):
self.__LAST_COUNT = 10
self.__left = []
self.__right = []
def addText(self, text):
"""
:type text: str
:rtype: None
"""
for x in text:
self.__left.append(x)
def deleteText(self, k):
"""
:type k: int
:rtype: int
"""
return self.__move(k, self.__left, None)
def cursorLeft(self, k):
"""
:type k: int
:rtype: str
"""
self.__move(k, self.__left, self.__right)
return self.__last_characters()
def cursorRight(self, k):
"""
:type k: int
:rtype: str
"""
self.__move(k, self.__right, self.__left)
return self.__last_characters()
def __move(self, k, src, dst):
cnt = min(k, len(src))
for _ in xrange(cnt):
if dst is not None:
dst.append(src[-1])
src.pop()
return cnt
def __last_characters(self):
return "".join(self.__left[-self.__LAST_COUNT:])