1472.设计浏览器历史记录(中等)

1472.设计浏览器历史记录(中等) (opens new window)

解法:模拟

采用slice存储历史记录,并用slice的长度为隐性判断记录历史记录最大值。指针记录当前浏览页面,防止越界即可。

type BrowserHistory struct {
	point int
	urls  []string
}

func Constructor(homepage string) BrowserHistory {
	return BrowserHistory{point: 0, urls: []string{homepage}}
}

func (this *BrowserHistory) Visit(url string) {
	this.urls = append(this.urls[:this.point+1], url)
	this.point +=1
}

func (this *BrowserHistory) Back(steps int) string {
	this.point = this.point - steps
	if this.point < 0 {
		this.point = 0
	}
	return this.urls[this.point]
}

func (this *BrowserHistory) Forward(steps int) string {
	this.point = this.point + steps
	if this.point>= len(this.urls){
		this.point = len(this.urls) - 1
	}
	return this.urls[this.point]
}