1871. Jump Game VII

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), and
  • s[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的开销比较大,因此时间并不是很理想

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值