|
| 1 | +export interface MyNode { |
| 2 | + val: string |
| 3 | + prev: MyNode | null |
| 4 | + next: MyNode | null |
| 5 | +} |
| 6 | + |
| 7 | +class TextEditor { |
| 8 | + cursor: MyNode |
| 9 | + constructor () { |
| 10 | + this.cursor = { |
| 11 | + val: '#', |
| 12 | + prev: null, |
| 13 | + next: null |
| 14 | + } |
| 15 | + } |
| 16 | + |
| 17 | + addText (text: string): void { |
| 18 | + for (const ch of text) { |
| 19 | + const newNode = { |
| 20 | + val: ch, |
| 21 | + prev: this.cursor, |
| 22 | + next: this.cursor.next |
| 23 | + } |
| 24 | + if (this.cursor.next) this.cursor.next.prev = newNode |
| 25 | + this.cursor.next = newNode |
| 26 | + this.cursor = this.cursor.next |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + deleteText (k: number): number { |
| 31 | + let cnt = 0 |
| 32 | + while (k-- && this.cursor.prev) { |
| 33 | + this.cursor.prev.next = this.cursor.next |
| 34 | + if (this.cursor.next) this.cursor.next.prev = this.cursor.prev |
| 35 | + this.cursor = this.cursor.prev |
| 36 | + cnt++ |
| 37 | + } |
| 38 | + return cnt |
| 39 | + } |
| 40 | + |
| 41 | + getLast10 (): string { |
| 42 | + let p: MyNode | null = this.cursor; let cnt = 10 |
| 43 | + const a = [] |
| 44 | + while (cnt-- && p && p.val !== '#') { |
| 45 | + a.push(p.val) |
| 46 | + p = p.prev |
| 47 | + } |
| 48 | + return a.reverse().join('') |
| 49 | + } |
| 50 | + |
| 51 | + cursorLeft (k: number): string { |
| 52 | + while (k-- && this.cursor.prev) { |
| 53 | + this.cursor = this.cursor.prev |
| 54 | + } |
| 55 | + return this.getLast10() |
| 56 | + } |
| 57 | + |
| 58 | + cursorRight (k: number): string { |
| 59 | + while (k-- && this.cursor.next) { |
| 60 | + this.cursor = this.cursor.next |
| 61 | + } |
| 62 | + return this.getLast10() |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +/** |
| 67 | +* Your TextEditor object will be instantiated and called as such: |
| 68 | +* var obj = new TextEditor() |
| 69 | +* obj.addText(text) |
| 70 | +* var param_2 = obj.deleteText(k) |
| 71 | +* var param_3 = obj.cursorLeft(k) |
| 72 | +* var param_4 = obj.cursorRight(k) |
| 73 | +*/ |
0 commit comments