leetcode 838. 推多米诺

题目链接
思路一:广度优先搜索
分析:每个骨牌的倒伏状态只和周围的骨牌受力状态有关,那么我们首先拿到所有在一开始受力的骨牌,并且记录一下方向,把这些最开始受力的骨牌放到队列中,然后进行广度搜索即可。每个骨牌的下一个骨牌就是在当前骨牌受力方向的下一个。
代码:

class Solution {
    public String pushDominoes(String dominoes) {
        char[] cs = dominoes.toCharArray();
        Queue<int[]> queue = new LinkedList<>();// location,forwarding,time    当前位置,受力方向,时间
        int[] ts = new int[cs.length];//记录是第几次受力

        for(int i =0; i<cs.length;i++){
            if(cs[i]=='.') continue;
            int forwarding = cs[i] == 'L' ? -1 : 1;
            queue.add(new int[]{i,forwarding,1});
            ts[i] = 1;
        }

        while (!queue.isEmpty()){
            int[] top = queue.poll();
            int nextLoc = top[0] + top[1];
            //如果当前是'.'那么说明肯定是之前多次受力调整回来了
            //下一次位置不能出界
            if(cs[top[0]]=='.' || nextLoc<0 || nextLoc>=cs.length) continue;
            if(ts[nextLoc] == 0){// 首次受力
                queue.add(new int[]{nextLoc,top[1],top[2]+1});
                cs[nextLoc] = top[1] == -1 ? 'L' : 'R';
                ts[nextLoc] = top[2] + 1;
            } else if(ts[nextLoc] == top[2] + 1){//同一时刻 多次受力
                //恢复直立状态
                cs[nextLoc] = '.';
            }
        }
        return String.valueOf(cs);
    }
}

思路二:双指针+模拟
分析:只有是’.'的才有可能被更改,那么我们可以总结出这么几种情况

  1. L…L
  2. R…R
  3. R…L
    还有一种L…R的情况,不过中间的是不需要变的。
    现在问题在于我们需要找到一段连续的…,我们可以用两个指针指向这段连续的…,我这里使用的是左闭右开区间。
    当找到这段连续的…后,那么就根据上面的三种情况分别进行处理即可。
    代码:
public String pushDominoes(String dominoes) {
        char[] cs = dominoes.toCharArray();
        int len = cs.length;
        for(int i = 0; i < len; i++){
            if(cs[i]=='.'){
                int l = i;
                while (i < len && cs[i]=='.'){
                    i++;
                }
                int r = i;
                if(l==0 || cs[l-1]=='L'){
                    if(r<len && cs[r]=='L'){// L....L
                        for(int j = l; j < r;j++){
                            cs[j] = 'L';
                        }
                    }
                }else{// cs[l-1]=='R'
                    if(r<len && cs[r]=='R'){// R....R
                        for(int j = l; j<r;j++){
                            cs[j] = 'R';
                        }
                    }else{//R ..... L
                        while (l<r-1){
                            cs[l] = 'R';
                            cs[r-1] = 'L';
                            l++;
                            r--;
                        }
                    }
                }
            }
        }
        return String.valueOf(cs);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值