自然而然的想到使用双向链表
初始化一个head和tail,构建成双向链表。point表示当前光标的位置,leftCount和rightCount分别表示point离head和tail的距离。cursorLeft函数和cursorRight函数需要根据这个距离做不同的处理。增加文本和删除文本都需要修改leftCount的值,而移动光标(cursorLeft函数和cursorRight函数)需要修改leftCount和rightCount的值。
直接看代码吧,逻辑不复杂。
class TextEditor {
Node head;
Node tail;
Node point;
int leftCount = 0;
int rightCount = 0;
public TextEditor() {
head = new Node();
tail = new Node();
point = head;
head.next = tail;
tail.pre = head;
}
public void addText(String text) {
Node next = point.next;
for(int i = 0; i < text.length(); i++) {
char charAt = text.charAt(i);
Node node = new Node();
node.c = charAt;
point.next = node;
node.pre = point;
point = node;
leftCount++;
}
point.next = next;
next.pre = point;
}
public int deleteText(int k) {
if(k > leftCount){
head.next = point.next;
point = head;
int temp = leftCount;
leftCount = 0;
return temp;
}
Node tempNode = point.next;
for(int i = 0; i < k; i++) {
point = point.pre;
}
point.next = tempNode;
tempNode.pre = point;
leftCount -= k;
return k;
}
public String cursorLeft(int k) {
if(k > leftCount) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < leftCount; i++) {
point = point.pre;
}
rightCount += leftCount;
leftCount = 0;
return getString();
}
for(int i = 0; i < k; i++) {
point = point.pre;
}
leftCount -= k;
rightCount += k;
return getString();
}
public String cursorRight(int k) {
if(k > rightCount) {
for(int i = 0; i < rightCount; i++) {
point = point.next;
}
leftCount += rightCount;
rightCount = 0;
return getString();
}
for(int i = 0; i < k; i++) {
point = point.next;
}
rightCount -= k;
leftCount += k;
return getString();
}
private String getString(){
StringBuilder sb = new StringBuilder();
Node tempNode = point;
int temp = Math.min(10, leftCount);
for(int i = 0; i < temp; i++) {
sb.append(tempNode.c);
tempNode = tempNode.pre;
}
return sb.reverse().toString();
}
}
class Node {
Character c;
Node pre;
Node next;
}
结果,中规中矩的结果