Jump Game VII LeetCode solution in Java

1
class Solution {
2
public boolean canReach(String s, int minJump, int maxJump) {
3
if (s.charAt(s.length() - 1) != '0') return false;
4

5
Queue<Integer> queue = new LinkedList<>();
6
queue.add(0);
7

8
// This variable tells us till which index we have processed
9
int maxReach = 0;
10

11
while (!queue.isEmpty()) {
12
int idx = queue.remove();
13
// If we reached the last index
14
if (idx == s.length() - 1) return true;
15

16
// start the loop from max of [current maximum (idx + minJump), maximum processed index
17
// (maxReach)]
18
for (int j = Math.max(idx + minJump, maxReach);
19
j <= Math.min(idx + maxJump, s.length() - 1);
20
j++) {
21
if (s.charAt(j) == '0') queue.add(j);
22
}
23

24
// since we have processed till idx + maxJump so update maxReach to next index
25
maxReach = Math.min(idx + maxJump + 1, s.length() - 1);
26
}
27

28
return false;
29
}
30
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0