Leetcode 1472. Design Browser History

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1472. Design Browser History相关的知识,希望对你有一定的参考价值。

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Design Browser History

2. Solution

**解析:**通过索引来控制要访问的页面,用列表存放页面,根据题目要求实现对应操作即可。

  • Version 1
class BrowserHistory:

    def __init__(self, homepage: str):
        self.pages = [homepage]
        self.index = 0


    def visit(self, url: str) -> None:
        self.pages = self.pages[:self.index+1]
        self.pages.append(url)
        self.index += 1


    def back(self, steps: int) -> str:
        self.index -= steps
        if self.index < 0:
            self.index = 0
        return self.pages[self.index]


    def forward(self, steps: int) -> str:
        self.index += steps
        if self.index >= len(self.pages):
            self.index = len(self.pages) - 1
        return self.pages[self.index]


# Your BrowserHistory object will be instantiated and called as such:
# obj = BrowserHistory(homepage)
# obj.visit(url)
# param_2 = obj.back(steps)
# param_3 = obj.forward(steps)
  • Version 2
class BrowserHistory:

    def __init__(self, homepage: str):
        self.pages = [homepage]
        self.index = 0
        

    def visit(self, url: str) -> None:
        self.pages = self.pages[:self.index+1]
        self.pages.append(url)
        self.index += 1
        

    def back(self, steps: int) -> str:
        self.index -= steps
        self.index = max(self.index, 0)
        return self.pages[self.index]
        

    def forward(self, steps: int) -> str:
        self.index += steps
        self.index = min(self.index, len(self.pages) - 1)
        return self.pages[self.index]


# Your BrowserHistory object will be instantiated and called as such:
# obj = BrowserHistory(homepage)
# obj.visit(url)
# param_2 = obj.back(steps)
# param_3 = obj.forward(steps)

Reference

  1. https://leetcode.com/problems/design-browser-history/

以上是关于Leetcode 1472. Design Browser History的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Algorithm 1472. 设计浏览器历史记录

LeetCode Algorithm 1472. 设计浏览器历史记录

LeetCode Algorithm 1472. 设计浏览器历史记录

leetcode 355 Design Twitte

LeetCode 706. Design HashMap

LeetCode Design Hit Counter