|
| 1 | +/** |
| 2 | + * 2147. Number of Ways to Divide a Long Corridor |
| 3 | + * https://leetcode.com/problems/number-of-ways-to-divide-a-long-corridor/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Along a long library corridor, there is a line of seats and decorative plants. You are given |
| 7 | + * a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' |
| 8 | + * represents a seat and each 'P' represents a plant. |
| 9 | + * |
| 10 | + * One room divider has already been installed to the left of index 0, and another to the right |
| 11 | + * of index n - 1. Additional room dividers can be installed. For each position between indices |
| 12 | + * i - 1 and i (1 <= i <= n - 1), at most one divider can be installed. |
| 13 | + * |
| 14 | + * Divide the corridor into non-overlapping sections, where each section has exactly two seats |
| 15 | + * with any number of plants. There may be multiple ways to perform the division. Two ways are |
| 16 | + * different if there is a position with a room divider installed in the first way but not in |
| 17 | + * the second way. |
| 18 | + * |
| 19 | + * Return the number of ways to divide the corridor. Since the answer may be very large, return |
| 20 | + * it modulo 109 + 7. If there is no way, return 0. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {string} corridor |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var numberOfWays = function(corridor) { |
| 28 | + const MOD = 1e9 + 7; |
| 29 | + let seatCount = 0; |
| 30 | + let result = 1; |
| 31 | + let lastPairEnd = -1; |
| 32 | + |
| 33 | + for (let i = 0; i < corridor.length; i++) { |
| 34 | + if (corridor[i] === 'S') { |
| 35 | + seatCount++; |
| 36 | + } |
| 37 | + } |
| 38 | + if (seatCount === 0 || seatCount % 2 !== 0) { |
| 39 | + return 0; |
| 40 | + } |
| 41 | + |
| 42 | + seatCount = 0; |
| 43 | + |
| 44 | + for (let i = 0; i < corridor.length; i++) { |
| 45 | + if (corridor[i] === 'S') { |
| 46 | + seatCount++; |
| 47 | + |
| 48 | + if (seatCount % 2 === 0) { |
| 49 | + lastPairEnd = i; |
| 50 | + } else if (seatCount > 1) { |
| 51 | + const plantsCount = i - lastPairEnd - 1; |
| 52 | + result = (result * (plantsCount + 1)) % MOD; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + return result; |
| 58 | +}; |
0 commit comments