Leetcode 1472. Design Browser History

Problem

You have a browser of one tab where you start on the homepage and you can visit another url, get back in the history number of steps or move forward in the history number of steps.

Implement the BrowserHistory class:

  • BrowserHistory(string homepage) Initializes the object with the homepage of the browser.
  • void visit(string url) Visits url from the current page. It clears up all the forward history.
  • string back(int steps) Move steps back in history. If you can only return x steps in the history and steps > x, you will return only x steps. Return the current url after moving back in history at most steps.
  • string forward(int steps) Move steps forward in history. If you can only forward x steps in the history and steps > x, you will forward only x steps. Return the current url after forwarding in history at most steps.

Algorithm

Using a list to record website addresses and simulating access.

Code

class BrowserHistory:

    def __init__(self, homepage: str):
        self.history = [homepage]
        self.index = 0
        self.size = 1
        self.max_size = 1

    def visit(self, url: str) -> None:
        self.index += 1
        if self.index == self.max_size:
            self.history.append(url)
            self.max_size += 1
            self.size += 1
        else:
            self.history[self.index] = url
            self.size = self.index + 1

    def back(self, steps: int) -> str:
        while self.index > 0 and steps > 0:
            self.index -= 1
            steps -= 1
        return self.history[self.index]

    def forward(self, steps: int) -> str:
        while self.index < self.size-1 and steps > 0:
            self.index += 1
            steps -= 1
        return self.history[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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值