-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
1871-jump-game-vii.kt
48 lines (41 loc) · 1.16 KB
/
1871-jump-game-vii.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
/*
* O(n) BFS
*/
class Solution {
fun canReach(s: String, minJump: Int, maxJump: Int): Boolean {
val q = LinkedList<Int>().apply { add(0) }
var farthest = 0
with (q) {
while (isNotEmpty()) {
val i = removeFirst()
val start = maxOf(i + minJump, farthest + 1)
for (j in start until minOf(i + maxJump + 1, s.length)) {
if (s[j] == '0') {
if (j == s.lastIndex)
return true
addLast(j)
}
}
farthest = i + maxJump
}
}
return false
}
}
/*
* O(n) DP
*/
class Solution {
fun canReach(s: String, minJump: Int, maxJump: Int): Boolean {
val dp = BooleanArray(s.length).apply { this[0] = true }
var cntOfPos = 0
for (i in 1 until s.length) {
if (i - minJump >= 0 && dp[i - minJump])
cntOfPos++
if (i - maxJump > 0 && dp[i - maxJump - 1])
cntOfPos--
dp[i] = cntOfPos > 0 && s[i] == '0'
}
return dp[s.lastIndex]
}
}