Design Browser History LeetCode solution in Java

1
class BrowserHistory {
2
int current;
3
ArrayList<String> history;
4

5
public BrowserHistory(String homepage) {
6
this.history = new ArrayList<>();
7
history.add(homepage);
8
this.current = 0;
9
}
10

11
public void visit(String url) {
12
while (history.size() - 1 > current) { // delete forward history
13
history.remove(
14
history.size() - 1); // which means delete everything beyond our current website
15
}
16
history.add(url);
17
++current;
18
}
19

20
public String back(int steps) {
21
if (steps > current)
22
current = 0; // if we can't get enough back, we return first thing in our history
23
else current -= steps; // if there will be no arrayindexoutofrange error, go back
24
return history.get(current); // return current webpage
25
}
26

27
public String forward(int steps) {
28
// if we are going to move more than our arraylist, then we will return the last element
29
if (steps + current >= history.size()) current = history.size() - 1;
30
else current += steps; // if there will be no arrayindexoutofrange error, go forward!
31
return history.get(current); // return the current webpage
32
}
33
}
34

35
/**
36
* Your BrowserHistory object will be instantiated and called as such: BrowserHistory obj = new
37
* BrowserHistory(homepage); obj.visit(url); String param_2 = obj.back(steps); String param_3 =
38
* obj.forward(steps);
39
*/

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0