August 22, 2022

2296. Design a Text Editor

2296. Design a Text Editor

Use StringBuilder.

class TextEditor {
    StringBuilder sb;
    int index;

    public TextEditor() {
        // 0 1 2 3 4 5 6
        // h e l l | o 
        sb = new StringBuilder();
        index = 0;
    }
    
    public void addText(String text) {
        sb.insert(index, text);
        index += text.length();
    }
    
    public int deleteText(int k) {
        int tmp = index;
        index -= k;
        if (index < 0) {
            index = 0;
        }
        sb.delete(index, tmp);
        return tmp - index;
    }
    
    public String cursorLeft(int k) {
        index -= k;
        if (index < 0) {
            index = 0;
        }
        if (index < 10) {
            return sb.substring(0, index);
        } else {
            return sb.substring(index - 10, index);
        }
    }
    
    public String cursorRight(int k) {
        index += k;
        if (index > sb.length()) {
            index = sb.length();
        }
        if (index < 10) {
            return sb.substring(0, index);
        } else {
            return sb.substring(index - 10, index);
        }
    }
}

/**
 * Your TextEditor object will be instantiated and called as such:
 * TextEditor obj = new TextEditor();
 * obj.addText(text);
 * int param_2 = obj.deleteText(k);
 * String param_3 = obj.cursorLeft(k);
 * String param_4 = obj.cursorRight(k);
 */
comments powered by Disqus