Skip to content

2296. Design a Text Editor

  • Time:
    • Constructor: $O(1)$
    • addText(text: str): $O(|\texttt{text}|)$
    • deleteText(k: int): $O(k)$
    • cursorLeft(k: int): $O(k)$
    • cursorRight(k: int): $O(k)$
  • Space: $O(|\texttt{s}|)$
 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
class TextEditor {
 public:
  void addText(string text) {
    s += text;
  }

  int deleteText(int k) {
    const int numDeleted = min(k, static_cast<int>(s.length()));
    for (int i = 0; i < numDeleted; ++i)
      s.pop_back();
    return numDeleted;
  }

  string cursorLeft(int k) {
    while (!s.empty() && k--)
      stack.push(s.back()), s.pop_back();
    return getString();
  }

  string cursorRight(int k) {
    while (!stack.empty() && k--)
      s += stack.top(), stack.pop();
    return getString();
  }

  string getString() {
    if (s.length() < 10)
      return s;
    return s.substr(s.length() - 10);
  }

 private:
  string s;
  stack<char> stack;
};
 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
class TextEditor {
  public void addText(String text) {
    sb.append(text);
  }

  public int deleteText(int k) {
    final int numDeleted = Math.min(k, sb.length());
    for (int i = 0; i < numDeleted; ++i)
      sb.deleteCharAt(sb.length() - 1);
    return numDeleted;
  }

  public String cursorLeft(int k) {
    while (!sb.isEmpty() && k-- > 0) {
      stack.push(sb.charAt(sb.length() - 1));
      sb.deleteCharAt(sb.length() - 1);
    }
    return getString();
  }

  public String cursorRight(int k) {
    while (!stack.isEmpty() && k-- > 0)
      sb.append(stack.pop());
    return getString();
  }

  private String getString() {
    if (sb.length() < 10)
      return sb.toString();
    return sb.substring(sb.length() - 10).toString();
  }

  private StringBuilder sb = new StringBuilder();
  private Deque<Character> stack = new ArrayDeque<>();
}
 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
class TextEditor:
  def __init__(self):
    self.s = []
    self.stack = []

  def addText(self, text: str) -> None:
    for c in text:
      self.s.append(c)

  def deleteText(self, k: int) -> int:
    numDeleted = min(k, len(self.s))
    for _ in range(numDeleted):
      self.s.pop()
    return numDeleted

  def cursorLeft(self, k: int) -> str:
    while self.s and k > 0:
      self.stack.append(self.s.pop())
      k -= 1
    return self._getString()

  def cursorRight(self, k: int) -> str:
    while self.stack and k > 0:
      self.s.append(self.stack.pop())
      k -= 1
    return self._getString()

  def _getString(self) -> str:
    if len(self.s) < 10:
      return ''.join(self.s)
    return ''.join(self.s[-10:])