2147. Number of Ways to Divide a Long Corridor
分隔长走廊的方案数
Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters S and P where each S represents a seat and each P represents a plant.
一条长长的图书馆走廊上,排列着一排座椅和装饰性植物。给你一个长度为 n 的、下标从 0 开始的字符串 corridor ,该字符串仅由字母 S 和 P 组成,其中每个 S 表示一张座椅,每个 P 表示一株植物。
One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed.
已在索引 0 左侧安装了一道房间隔断,在索引 n - 1 右侧也已安装了一道房间隔断。你还可以在其他位置安装额外的房间隔断。对于任意两个索引 i - 1 和 i 之间的位置(即 1 <= i <= n - 1 ),最多只能安装一道隔断。
Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way.
将走廊划分为若干个互不重叠的区间,使得每个区间内恰好包含两张座椅,且可包含任意数量的植物。可能存在多种划分方式。若两种划分方式中存在某个位置,在第一种方式中安装了房间隔断,而在第二种方式中未安装,则认为这两种方式不同。
Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 1^9 + 7. If there is no way, return 0.
返回划分走廊的方案数。由于答案可能非常大,请返回其对 109 + 7 取模的结果。若不存在可行的划分方式,则返回 0 。
Example 1: 示例 1:
Input: corridor = "SSPPSPS"
Output: 3
Explanation: There are 3 different ways to divide the corridor.
The black bars in the above image indicate the two room dividers already installed.
Note that in each of the ways, each section has exactly two seats.
Ways of solving a problem 解题思路
- 每段必须有2个座位,则座位数必须是偶数且大于0
- 记录每个座位的下标
- 计算第
2i个座位与第2i -1个座位之间存在的花盆数 + 1,即为可以放隔板的数量
class Solution {
public:
int numberOfWays(string corridor) {
const int MOD = 1e9 + 7;
vector<int> seats;
for (int i = 0; i < corridor.size(); ++i) {
if (corridor[i] == 'S') {
seats.push_back(i);
}
}
int m = seats.size();
if (m == 0 || m % 2 != 0) {
return 0;
}
long long ans = 1;
for (int i = 1; i < m / 2; ++i) {
int gap = seats[2 * i] - seats[2 * i - 1] - 1; // 花盆数
ans = ans * (gap + 1) % MOD;
}
return (int)ans;
}
};

浙公网安备 33010602011771号