Leetcode 1472. Design Browser History

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

1. Description

Design Browser History

2. Solution

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

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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/
如果有收获,可以请我喝杯咖啡!