forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1472-design-browser-history.kt
84 lines (70 loc) · 1.71 KB
/
1472-design-browser-history.kt
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
* Using an ArrayList
*/
class BrowserHistory(homepage: String) {
val history = ArrayList<String>()
var size = 0
var index = 0
init {
history.add(homepage)
size = 1
}
fun visit(url: String) {
if(history.size < index + 2)
history.add(url)
else
history[index + 1] = url
index++
size = index + 1
}
fun back(steps: Int): String {
index = maxOf(index - steps, 0)
return history[index]
}
fun forward(steps: Int): String {
index = minOf(index + steps, size - 1)
return history[index]
}
}
/*
* Using a Doubly-LinkedList
*/
class BrowserNode(val page: String) {
var next: BrowserNode? = null
var prev: BrowserNode? = null
}
class BrowserHistory(homepage: String) {
var current: BrowserNode? = null
init {
current = BrowserNode(homepage)
}
fun visit(url: String) {
val temp = BrowserNode(url)
current?.next = temp
temp.prev = current
current = current?.next
}
fun back(steps: Int): String {
var stepsTaken = 0
while(current?.prev != null && stepsTaken < steps) {
current = current?.prev
stepsTaken++
}
return current!!.page
}
fun forward(steps: Int): String {
var stepsTaken = 0
while(current?.next != null && stepsTaken < steps) {
current = current?.next
stepsTaken++
}
return current!!.page
}
}
/**
* Your BrowserHistory object will be instantiated and called as such:
* var obj = BrowserHistory(homepage)
* obj.visit(url)
* var param_2 = obj.back(steps)
* var param_3 = obj.forward(steps)
*/