Leetcode70场双周赛-第四题2147. 分隔长廊的方案数

题目描述

2147. 分隔长廊的方案数

解题思想

进行一轮遍历,每次循环中,找三把椅子。记录第三把椅子的位置。只有在第三把椅子和第二把椅子之间可以放屏风,这两把椅子之间有可以通过下标相减得出。假如找不到第一把、第二把椅子,那就是0。假如找不到第三把,那就可以结束了。

解题代码

public class Solution2147 {
    public static void main(String[] args) {
        String k =
                "PPPPPPPSPPPSPPPPSPPPSPPPPPSPPPSPPSPPSPPPPPSPSPPPPPSPPSPPPPPSPPSPPSPPPSPP" +
                        "PPSPPPPSPPPPPSPSPPPPSPSPPPSPPPPSPPPPPSPSPPSPPPPSPPSPPSPPSPPPSPPSPSPPSSSS";
        // 18335643
        System.out.println(new Solution2147().numberOfWays(k));
    }

    public int numberOfWays(String corridor) {
        final int MOD = 1000000007;
        final char CHAIR = 'S';// 定义椅子
        int start = 0;
        int end = corridor.length() - 1;
        int index3 = start;
        long res = 1;
        while (index3 <= end) {

            // 寻找第一把椅子
            int index1 = index3;
            int count = 0;
            while (index1 <= end) {
                if (corridor.charAt(index1) == CHAIR) {
                    count++;
                    break;
                }
                index1++;
            }
            if (count == 0) {
                // 根本没有第一把椅子
                return 0;
            }

            // 寻找第二把椅子
            int index2 = index1 + 1;
            while (index2 <= end) {
                if (corridor.charAt(index2) == CHAIR) {
                    count++;
                    break;
                }
                index2++;
            }
            if (count != 2) {
                // 根本没有第二把椅子
                return 0;
            }

            // 找到了两把椅子,坐标分别为 index1 index2,开始找下一把
            index3 = index2 + 1;
            while (index3 <= end) {
                if (corridor.charAt(index3) == CHAIR) {
                    break;
                }
                index3++;
            }

            if (index3 > end) {
                //已经找不到下一把椅子了,直接结束了。最后找到的两把椅子,只能组成一种
                break;
            }
            res = (res * (index3 - index2)) % MOD;

        }
        return (int) (res % MOD);
    }

}

解题结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

康雨城

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值