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
题目:给一串字符数组,最小跳的步数和最大跳步数。从0位置开始起跳,只能在‘0’位置落脚。问能否跳到最后位置。
思路:用一个queue来存放所有可以达到的位置。这个位置必须是‘0’,而且大于等于起跳位置+minJump,小于等于起跳位置+maxJump。队列头存放的是当前起跳位置。
代码:
class Solution {
public:
bool canReach(string s, int minJump, int maxJump) {
if(s.back() != '0') return false;
queue<int> q;
int last = 0;
q.push(0);
while(!q.empty() && last < s.length()-1){
int next = s.find('0', last+1);
while(!q.empty() && q.front()+maxJump < next) q.pop(); //寻找能满足最大跳跳到next处的起跳位置
if(q.empty()) return false; //如果找不到则证明跳不到next位置,那肯定也跳不到最后位置
if(q.front()+minJump <= next) //如果通过最小跳也能到达next位置,则push进queue
q.push(next);
else if(next == s.length()-1) //next位置到达不了,如果是最后一个直接返回false
return false;
last = next;
}
return true;
}
};
time: O(N), space:O(maxJump)。线性时间,但用queue的开销比较大,因此时间并不是很理想