Q28-code1472- 设计浏览器历史记录

18 阅读1分钟

实现思路

方法1:栈 + 截断法

1 关键是要注意 visit的要求:需要删除 浏览历史里 全部前进的记录

  • 实现方法是 通过slice方法 截断在这之后的历史数据

2 steps 和 x 的合法性判断

  • 通过 Math.min/max 来进行边界限制

参考文档

01-直接参考实现

代码实现

1 方法1: 栈 + 截断法 时间复杂度: O(1); 空间复杂度(n)

class BrowserHistory {
  st: Array<string>;
  curIdx: number;
  constructor(homepage: string) {
    this.st = [homepage];
    this.curIdx = 0;
  }

  visit(url: string): void {
    // 当从历史中间位置访问新URL时,需要截断后续历史
    this.st = this.st.slice(0, this.curIdx + 1);
    this.st.push(url);
    this.curIdx++;
  }

  back(steps: number): string {
    this.curIdx = Math.max(0, this.curIdx - steps);
    return this.st[this.curIdx];
  }

  forward(steps: number): string {
    this.curIdx = Math.min(this.st.length - 1, this.curIdx + steps);
    return this.st[this.curIdx];
  }
}