1472.设计浏览器历史记录

Posted by 云起 on 2025-02-26
Estimated Reading Time 1 Minutes
Words 186 In Total
Viewed Times

1472.设计浏览器历史记录

地址:1472. 设计浏览器历史记录 - 力扣(LeetCode)

思路

维护历史数组,通过当前下标来模拟操作。

代码中的resize可以帮助直接擦除当前访问之后的页面。

代码

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
33
34
class BrowserHistory {
public:
vector<string> history;
int idx=-1;
BrowserHistory(string homepage) {
history.resize(0);
history.push_back(homepage);
idx=0;
}

void visit(string url) {
history.resize(idx+1);
history.push_back(url);
idx=history.size()-1;
}

string back(int steps) {
idx-steps>=0?idx=idx-steps:idx=0;
return history[idx];
}

string forward(int steps) {
idx+steps>=history.size()?idx=history.size()-1:idx=idx+steps;
return history[idx];
}
};

/**
* Your BrowserHistory object will be instantiated and called as such:
* BrowserHistory* obj = new BrowserHistory(homepage);
* obj->visit(url);
* string param_2 = obj->back(steps);
* string param_3 = obj->forward(steps);
*/

复杂度

O(n)


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !