2296. Design a Text Editor Hard

@problem@discussion
#Linked List#String#Stack#Design#Simulation#Doubly-Linked List



1/**
2 * [2296] Design a Text Editor
3 *
4 * Design a text editor with a cursor that can do the following:
5 *
6 * Add text to where the cursor is.
7 * Delete text from where the cursor is (simulating the backspace key).
8 * Move the cursor either left or right.
9 *
10 * When deleting text, only characters to the left of the cursor will be deleted. The cursor will also remain within the actual text and cannot be moved beyond it. More formally, we have that 0 <= cursor.position <= currentText.length always holds.
11 * Implement the TextEditor class:
12 *
13 * TextEditor() Initializes the object with empty text.
14 * void addText(string text) Appends text to where the cursor is. The cursor ends to the right of text.
15 * int deleteText(int k) Deletes k characters to the left of the cursor. Returns the number of characters actually deleted.
16 * string cursorLeft(int k) Moves the cursor to the left k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
17 * string cursorRight(int k) Moves the cursor to the right k times. Returns the last min(10, len) characters to the left of the cursor, where len is the number of characters to the left of the cursor.
18 *
19 *  
20 * Example 1:
21 *
22 * Input
23 * ["TextEditor", "addText", "deleteText", "addText", "cursorRight", "cursorLeft", "deleteText", "cursorLeft", "cursorRight"]
24 * [[], ["leetcode"], [4], ["practice"], [3], [8], [10], [2], [6]]
25 * Output
26 * [null, null, 4, null, "etpractice", "leet", 4, "", "practi"]
27 * Explanation
28 * TextEditor textEditor = new TextEditor(); // The current text is "|". (The '|' character represents the cursor)
29 * textEditor.addText("leetcode"); // The current text is "leetcode|".
30 * textEditor.deleteText(4); // return 4
31 *                           // The current text is "leet|".
32 *                           // 4 characters were deleted.
33 * textEditor.addText("practice"); // The current text is "leetpractice|".
34 * textEditor.cursorRight(3); // return "etpractice"
35 *                            // The current text is "leetpractice|".
36 *                            // The cursor cannot be moved beyond the actual text and thus did not move.
37 *                            // "etpractice" is the last 10 characters to the left of the cursor.
38 * textEditor.cursorLeft(8); // return "leet"
39 *                           // The current text is "leet|practice".
40 *                           // "leet" is the last min(10, 4) = 4 characters to the left of the cursor.
41 * textEditor.deleteText(10); // return 4
42 *                            // The current text is "|practice".
43 *                            // Only 4 characters were deleted.
44 * textEditor.cursorLeft(2); // return ""
45 *                           // The current text is "|practice".
46 *                           // The cursor cannot be moved beyond the actual text and thus did not move.
47 *                           // "" is the last min(10, 0) = 0 characters to the left of the cursor.
48 * textEditor.cursorRight(6); // return "practi"
49 *                            // The current text is "practi|ce".
50 *                            // "practi" is the last min(10, 6) = 6 characters to the left of the cursor.
51 *
52 *  
53 * Constraints:
54 *
55 * 1 <= text.length, k <= 40
56 * text consists of lowercase English letters.
57 * At most 2 * 10^4 calls in total will be made to addText, deleteText, cursorLeft and cursorRight.
58 *
59 *  
60 * Follow-up: Could you find a solution with time complexity of O(k) per call?
61 *
62 */
63pub struct Solution {}
64
65// problem: https://leetcode.com/problems/design-a-text-editor/
66// discuss: https://leetcode.com/problems/design-a-text-editor/discuss/?currentPage=1&orderBy=most_votes&query=
67
68// submission codes start here
69use std::cmp;
70struct TextEditor {
71    left: Vec<char>,
72    right: Vec<char>,
73}
74
75/**
76 * `&self` means the method takes an immutable reference.
77 * If you need a mutable reference, change it to `&mut self` instead.
78 */
79impl TextEditor {
80    fn new() -> Self {
81        TextEditor {
82            left: vec![],
83            right: vec![],
84        }
85    }
86
87    fn add_text(&mut self, text: String) {
88        for c in text.chars() {
89            self.left.push(c);
90        }
91    }
92
93    fn delete_text(&mut self, k: i32) -> i32 {
94        let n = cmp::min(k, self.left.len() as i32);
95        for _ in 0..n {
96            self.left.pop();
97        }
98        n
99    }
100
101    fn cursor_left(&mut self, k: i32) -> String {
102        let n = cmp::min(k, self.left.len() as i32);
103        for _ in 0..n {
104            let p = self.left.pop().unwrap();
105            self.right.push(p);
106        }
107
108        let slice = &self.left[cmp::max(self.left.len() as i32 - 10, 0) as usize..];
109        slice.iter().collect::<String>()
110    }
111
112    fn cursor_right(&mut self, k: i32) -> String {
113        let n = cmp::min(k, self.right.len() as i32);
114        for _ in 0..n {
115            let p = self.right.pop().unwrap();
116            self.left.push(p);
117        }
118        self.cursor_left(0)
119    }
120}
121
122/**
123 * Your TextEditor object will be instantiated and called as such:
124 * let obj = TextEditor::new();
125 * obj.add_text(text);
126 * let ret_2: i32 = obj.delete_text(k);
127 * let ret_3: String = obj.cursor_left(k);
128 * let ret_4: String = obj.cursor_right(k);
129 */
130
131// submission codes end
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    #[test]
138    fn test_2296() {
139        let mut e = TextEditor::new();
140        e.add_text("leetcode".to_string());
141        e.delete_text(1);
142        assert_eq!(e.cursor_left(0), "leetcod".to_string());
143        e.add_text("leetcode".to_string());
144        assert_eq!(e.cursor_right(1), "odleetcode".to_string());
145    }
146}
147


Back
© 2025 bowen.ge All Rights Reserved.