请你设计一个带光标的文本编辑器,它可以实现以下功能:
- 添加: 在光标所在处添加文本。
- 删除: 在光标所在处删除文本(模拟键盘的删除键)。
- 移动: 将光标往左或者往右移动。
当删除文本时,只有光标左边的字符会被删除。光标会留在文本内,也就是说任意时候0 <= cursor.position <= currentText.length 都成立。
请你实现 TextEditor 类:
TextEditor()用空文本初始化对象。void addText(string text)将text添加到光标所在位置。添加完后光标在text的右边。int deleteText(int k)删除光标左边k个字符。返回实际删除的字符数目。string cursorLeft(int k)将光标向左移动k次。返回移动后光标左边min(10, len)个字符,其中len是光标左边的字符数目。string cursorRight(int k)将光标向右移动k次。返回移动后光标左边min(10, len)个字符,其中len是光标左边的字符数目。
示例 1:
输入:
["TextEditor", "addText", "deleteText", "addText", "cursorRight","cursorLeft", "deleteText", "cursorLeft", "cursorRight"]
[[], ["leetcode"], [4], ["practice"], [3], [8], [10], [2], [6]]
输出:
[null, null, 4, null, "etpractice", "leet", 4, "", "practi"]
解释:
TextEditor textEditor = new TextEditor(); // 当前 text 为 "|" 。('|' 字符表示光标)
textEditor.addText("leetcode"); // 当前文本为 "leetcode|" 。
textEditor.deleteText(4); // 返回 4
// 当前文本为 "leet|" 。
// 删除了 4 个字符。
textEditor.addText("practice"); // 当前文本为 "leetpractice|" 。
textEditor.cursorRight(3); // 返回 "etpractice"
// 当前文本为 "leetpractice|".
// 光标无法移动到文本以外,所以无法移动。
// "etpractice" 是光标左边的 10 个字符。
textEditor.cursorLeft(8); // 返回 "leet"
// 当前文本为 "leet|practice" 。
// "leet" 是光标左边的 min(10, 4) = 4 个字符。
textEditor.deleteText(10); // 返回 4
// 当前文本为 "|practice" 。
// 只有 4 个字符被删除了。
textEditor.cursorLeft(2); // 返回 ""
// 当前文本为 "|practice" 。
// 光标无法移动到文本以外,所以无法移动。
// "" 是光标左边的 min(10, 0) = 0 个字符。
textEditor.cursorRight(6); // 返回 "practi"
// 当前文本为 "practi|ce" 。
// "practi" 是光标左边的 min(10, 6) = 6 个字符。
题解:
var TextEditor = function () {
this.str = ''
// 栈内存光标后面的值
this.t = []
};
/**
* @param {string} text
* @return {void}
*/
TextEditor.prototype.addText = function (text) {
this.str += text
};
/**
* @param {number} k
* @return {number}
*/
TextEditor.prototype.deleteText = function (k) {
// 字符串长度小于删除长度时 取字符串长度
if (this.str.length < k) k = this.str.length
this.str = this.str.slice(0, this.str.length - k)
return k
};
/**
* @param {number} k
* @return {string}
*/
TextEditor.prototype.cursorLeft = function (k) {
// 字符串长度小于向左移动长度时 取字符串长度
if (this.str.length < k) k = this.str.length
// 遍历向左移动时光标位置后面的值塞入栈内
for (let i = 0, j = this.str.length - 1; i < k; i++, j--) {
this.t.push(this.str[j])
}
this.str = this.str.slice(0, this.str.length - k)
return this.str.slice(-10)
};
/**
* @param {number} k
* @return {string}
*/
TextEditor.prototype.cursorRight = function (k) {
// 光标向右移动时 移动举例大于栈内值时 去栈内值
if (this.t.length < k) k = this.t.length
// 当栈内为空时说明光标在最后 如果栈内有值代表光标在字符串内
for (let i = 0; i < k; i++) {
this.str += this.t.pop()
}
return this.str.slice(-10)
};
/**
* Your TextEditor object will be instantiated and called as such:
* var obj = new TextEditor()
* obj.addText(text)
* var param_2 = obj.deleteText(k)
* var param_3 = obj.cursorLeft(k)
* var param_4 = obj.cursorRight(k)
*/
来源:力扣(LeetCode)
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。