|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Define the modulo constant |
| 4 | + int mod=1e9+7; |
| 5 | + |
| 6 | + int numberOfWays(string s) { |
| 7 | + |
| 8 | + int n=s.size(); |
| 9 | + int c=0; |
| 10 | + |
| 11 | + // Step 1: Count total seats |
| 12 | + for(int i=0; i<n; i++) |
| 13 | + { |
| 14 | + if(s[i]=='S') |
| 15 | + c++; |
| 16 | + } |
| 17 | + |
| 18 | + // Step 1: Edge Case Check |
| 19 | + // If total seats is 0 or odd, division is impossible. |
| 20 | + if(c==0 || c%2 != 0) |
| 21 | + return 0; |
| 22 | + // If total seats is exactly 2, the whole corridor is one section (1 way). |
| 23 | + if(c==2) |
| 24 | + return 1; |
| 25 | + |
| 26 | + // Use long long for result to safely handle intermediate products before modulo. |
| 27 | + long r=1; |
| 28 | + int seat=0; // Counts seats encountered so far |
| 29 | + int plant=0; // Counts plants in the current flexible gap |
| 30 | + |
| 31 | + // Step 2-4: Iterative Counting for Gaps |
| 32 | + for(int i=0; i<n; i++) |
| 33 | + { |
| 34 | + if(s[i]=='S') |
| 35 | + { |
| 36 | + seat++; |
| 37 | + } |
| 38 | + // If 'P' is encountered *after* an even number of seats (S_2, S_4, etc.) |
| 39 | + else if(seat>=2 && (seat%2)==0) |
| 40 | + { |
| 41 | + // This 'P' is in a flexible gap, e.g., between S_2 and S_3. |
| 42 | + plant++; |
| 43 | + } |
| 44 | + |
| 45 | + // This condition is met when we hit the next odd seat (S_3, S_5, etc.), |
| 46 | + // and we have plants in the gap (plant > 0). |
| 47 | + if(seat > 2 && seat%2 != 0 && plant > 0) |
| 48 | + { |
| 49 | + // The gap is closed. The number of ways to place the wall is plant + 1. |
| 50 | + // Apply the multiplication principle with modulo operation. |
| 51 | + r=((r%mod)*((plant+1)%mod))%mod; |
| 52 | + // Reset plant count for the next gap (e.g., between S_4 and S_5) |
| 53 | + plant=0; |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + // Step 5: Final Result |
| 58 | + return (int)r; |
| 59 | + } |
| 60 | +}; |
0 commit comments