Leetcode 1472. Design Browser History

2021-07-08 16:22:20 浏览数 (1)

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

1. Description

2. Solution

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

  • Version 1
代码语言:javascript复制
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
代码语言:javascript复制
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/

0 人点赞