1472. 设计浏览器历史记录
1472. 设计浏览器历史记录 - 力扣(LeetCode)
用一个列表(视作栈)维护浏览历史:初始化列表 history=[homepage],并初始化当前位置 cur=0。
visit:先把 cur 加一,把 history 中的从 cur 到末尾的字符串全部删除,然后把 url 加到 history 的末尾。
back:把 cur 更新为 max(cur−step,0),然后返回 history[cur]。
forward:把 cur 更新为 min(cur+step,n−1),其中 n 为 history 的长度,然后返回 history[cur]class BrowserHistory:def __init__(self, homepage: str):self.history = [homepage]self.cur = 0 # 当前页面是 history[cur]def visit(self, url: str) -> None:self.cur += 1del self.history[self.cur:] # 把浏览历史前进的记录全部删除self.history.append(url) # 从当前页跳转访问 url 对应的页面def back(self, steps: int) -> str:self.cur = max(self.cur - steps, 0) # 后退 steps 步return self.history[self.cur]def forward(self, steps: int) -> str:self.cur = min(self.cur + steps, len(self.history) - 1) # 前进 steps 步return self.history[self.cur]
