文章作者:Tyan 博客:noahsnail.com | CSDN | 简书
1. Description
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
- https://leetcode.com/problems/design-browser-history/