0
点赞
收藏
分享

微信扫一扫

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

搬砖的小木匠 2022-01-26 阅读 40
leetcodejava

题目描述

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);
    }

}

解题结果

 

举报

相关推荐

0 条评论