[LeetCode] Number of Ways to Divide a Long Corridor

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.

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.

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 109 + 7. If there is no way, return 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
int mod = 1e9 + 7;
public:
int numberOfWays(string corridor) {
int n = corridor.length(), seat = 0, counter = 0, totalSeat = 0;
unsigned long long res = 1;
for(int i = 0; i < n; i++) {
if(corridor[i] == 'S') {
seat++;
totalSeat++;
}
if(seat == 2) {
counter++;
} else if(seat > 2) {
res = (res * counter) % mod;
counter = 0;
seat = 1;
}
}
return totalSeat == 0 or totalSeat & 1 ? 0 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/13/PS/LeetCode/number-of-ways-to-divide-a-long-corridor/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.