comments | difficulty | edit_url | rating | source | tags | ||||
---|---|---|---|---|---|---|---|---|---|
true |
中等 |
1896 |
第 242 场周赛 Q3 |
|
给你一个下标从 0 开始的二进制字符串 s
和两个整数 minJump
和 maxJump
。一开始,你在下标 0
处,且该位置的值一定为 '0'
。当同时满足如下条件时,你可以从下标 i
移动到下标 j
处:
i + minJump <= j <= min(i + maxJump, s.length - 1)
且s[j] == '0'
.
如果你可以到达 s
的下标 s.length - 1
处,请你返回 true
,否则返回 false
。
示例 1:
输入:s = "011010", minJump = 2, maxJump = 3 输出:true 解释: 第一步,从下标 0 移动到下标 3 。 第二步,从下标 3 移动到下标 5 。
示例 2:
输入:s = "01101110", minJump = 2, maxJump = 3 输出:false
提示:
2 <= s.length <= 105
s[i]
要么是'0'
,要么是'1'
s[0] == '0'
1 <= minJump <= maxJump < s.length
我们定义一个长度为
考虑
最终答案即为
时间复杂度
class Solution:
def canReach(self, s: str, minJump: int, maxJump: int) -> bool:
n = len(s)
pre = [0] * (n + 1)
pre[1] = 1
f = [True] + [False] * (n - 1)
for i in range(1, n):
if s[i] == "0":
l, r = max(0, i - maxJump), i - minJump
f[i] = l <= r and pre[r + 1] - pre[l] > 0
pre[i + 1] = pre[i] + f[i]
return f[-1]
class Solution {
public boolean canReach(String s, int minJump, int maxJump) {
int n = s.length();
int[] pre = new int[n + 1];
pre[1] = 1;
boolean[] f = new boolean[n];
f[0] = true;
for (int i = 1; i < n; ++i) {
if (s.charAt(i) == '0') {
int l = Math.max(0, i - maxJump);
int r = i - minJump;
f[i] = l <= r && pre[r + 1] - pre[l] > 0;
}
pre[i + 1] = pre[i] + (f[i] ? 1 : 0);
}
return f[n - 1];
}
}
class Solution {
public:
bool canReach(string s, int minJump, int maxJump) {
int n = s.size();
int pre[n + 1];
memset(pre, 0, sizeof(pre));
pre[1] = 1;
bool f[n];
memset(f, 0, sizeof(f));
f[0] = true;
for (int i = 1; i < n; ++i) {
if (s[i] == '0') {
int l = max(0, i - maxJump);
int r = i - minJump;
f[i] = l <= r && pre[r + 1] - pre[l];
}
pre[i + 1] = pre[i] + f[i];
}
return f[n - 1];
}
};
func canReach(s string, minJump int, maxJump int) bool {
n := len(s)
pre := make([]int, n+1)
pre[1] = 1
f := make([]bool, n)
f[0] = true
for i := 1; i < n; i++ {
if s[i] == '0' {
l, r := max(0, i-maxJump), i-minJump
f[i] = l <= r && pre[r+1]-pre[l] > 0
}
pre[i+1] = pre[i]
if f[i] {
pre[i+1]++
}
}
return f[n-1]
}
function canReach(s: string, minJump: number, maxJump: number): boolean {
const n = s.length;
const pre: number[] = Array(n + 1).fill(0);
pre[1] = 1;
const f: boolean[] = Array(n).fill(false);
f[0] = true;
for (let i = 1; i < n; ++i) {
if (s[i] === '0') {
const [l, r] = [Math.max(0, i - maxJump), i - minJump];
f[i] = l <= r && pre[r + 1] - pre[l] > 0;
}
pre[i + 1] = pre[i] + (f[i] ? 1 : 0);
}
return f[n - 1];
}
/**
* @param {string} s
* @param {number} minJump
* @param {number} maxJump
* @return {boolean}
*/
var canReach = function (s, minJump, maxJump) {
const n = s.length;
const pre = Array(n + 1).fill(0);
pre[1] = 1;
const f = Array(n).fill(false);
f[0] = true;
for (let i = 1; i < n; ++i) {
if (s[i] === '0') {
const [l, r] = [Math.max(0, i - maxJump), i - minJump];
f[i] = l <= r && pre[r + 1] - pre[l] > 0;
}
pre[i + 1] = pre[i] + (f[i] ? 1 : 0);
}
return f[n - 1];
};