HTMLify

LeetCode - Design a Text Editor - Go
Views: 20 | Author: abh
type Char struct {
	Value string
	Prev *Char
	Next *Char
}

type TextEditor struct {
	Cursor *Char
}

func CursorChar() *Char {
	return &Char{"|", nil, nil}
}

func Constructor() TextEditor {
    var te TextEditor
	te.Cursor = CursorChar()
	return te
}

func (this *TextEditor) AddChar(char rune) {
	this.Cursor.Value = string(char)
	nn := this.Cursor.Next
	this.Cursor.Next = CursorChar()
	this.Cursor.Next.Prev = this.Cursor
	this.Cursor = this.Cursor.Next
	if nn != nil {
		this.Cursor.Next = nn
		nn.Prev = this.Cursor
	}
}

func (this *TextEditor) AddText(text string) {
	for _, c := range text {
		this.AddChar(c)
	}
}


func (this *TextEditor) DeleteText(k int) int {
	var deleted int
	for range k {
		if this.Cursor.Prev == nil {
			break
		}
		this.Cursor.Prev = this.Cursor.Prev.Prev
		if this.Cursor.Prev != nil {
			this.Cursor.Prev.Next = this.Cursor
		}
		deleted++
	}
	return deleted
}


func (this *TextEditor) CursorLeft(k int) string {
	for range k {
		if this.Cursor.Prev == nil {
			break
		}
		this.Cursor.Value = this.Cursor.Prev.Value
		this.Cursor.Prev.Value = "|"
		this.Cursor = this.Cursor.Prev
	}
	return this.LeftText()
}


func (this *TextEditor) CursorRight(k int) string {
	for range k {
		if this.Cursor.Next == nil {
			break
		}
		this.Cursor.Value = this.Cursor.Next.Value
		this.Cursor.Next.Value = "|"
		this.Cursor = this.Cursor.Next
	}
	return this.LeftText()
}

func (this *TextEditor) LeftText() string {
	var left_side string
	c := this.Cursor.Prev
	for len(left_side) < 10 && c != nil { 
		left_side = c.Value + left_side
		c = c.Prev
	}
	return left_side
}

func (this *TextEditor) Print() {
	l, r := "", ""
	c := this.Cursor
	lc := c.Prev
	for lc != nil {
		l = lc.Value + l
		lc = lc.Prev
	}

	rc := c.Next
	for rc != nil {
		r += rc.Value
		rc = rc.Next
	}
}

/**
 * Your TextEditor object will be instantiated and called as such:
 * obj := Constructor();
 * obj.AddText(text);
 * param_2 := obj.DeleteText(k);
 * param_3 := obj.CursorLeft(k);
 * param_4 := obj.CursorRight(k);
 */

Comments