You are given a 0-indexed binary string s
and two integers minJump
and maxJump
. In the beginning, you are standing at index 0
, which is equal to '0'
. You can move from index i
to index j
if the following conditions are fulfilled:
i + minJump <= j <= min(i + maxJump, s.length - 1)
, ands[j] == '0'
.
Return true
if you can reach index s.length - 1
in s
, or false
otherwise.
Example 1:
Input: s = "011010", minJump = 2, maxJump = 3 Output: true Explanation: In the first step, move from index 0 to index 3. In the second step, move from index 3 to index 5.
Example 2:
Input: s = "01101110", minJump = 2, maxJump = 3 Output: false
Constraints:
2 <= s.length <= 105
s[i]
is either'0'
or'1'
.s[0] == '0'
1 <= minJump <= maxJump < s.length
class Solution:
def canReach(self, s: str, minJump: int, maxJump: int) -> bool:
n = len(s)
dp = [False] * n
dp[0] = True
pre_sum = [0] * (n + 1)
pre_sum[1] = 1
for i in range(1, n):
if s[i] == '0':
l = max(0, i - maxJump)
r = i - minJump
if r >= l and pre_sum[r + 1] - pre_sum[l] > 0:
dp[i] = True
pre_sum[i + 1] = pre_sum[i] + dp[i]
return dp[n - 1]
class Solution {
public boolean canReach(String s, int minJump, int maxJump) {
int n = s.length();
boolean[] dp = new boolean[n];
dp[0] = true;
int[] preSum = new int[n + 1];
preSum[1] = 1;
for (int i = 1; i < n; ++i) {
if (s.charAt(i) == '0') {
int l = Math.max(0, i - maxJump);
int r = i - minJump;
if (r >= l && preSum[r + 1] - preSum[l] > 0) {
dp[i] = true;
}
}
preSum[i + 1] = preSum[i] + (dp[i] ? 1 : 0);
}
return dp[n - 1];
}
}
/**
* @param {string} s
* @param {number} minJump
* @param {number} maxJump
* @return {boolean}
*/
var canReach = function (s, minJump, maxJump) {
let n = s.length;
let dp = new Array(n).fill(0);
let sum = new Array(n + 1).fill(0);
dp[0] = 1;
sum[1] = 1;
for (let i = 1; i < n; i++) {
if (s.charAt(i) == '0') {
let left = Math.max(0, i - maxJump);
let right = i - minJump;
if (left <= right && sum[right + 1] - sum[left] > 0) {
dp[i] = 1;
}
}
sum[i + 1] = sum[i] + dp[i];
}
return dp.pop();
};