You are given a 0-indexed binary string s which represents the types of buildings along a street where:
s[i] = '0' denotes that the ith building is an office and
s[i] = '1' denotes that the ith building is a restaurant.
As a city official, you would like to select 3 buildings for random inspection. However, to ensure variety, no two consecutive buildings out of the selected buildings can be of the same type.
For example, given s = "0 _**0**_ 1 _**1**_ 0 _**1**_ ", we cannot select the 1st, 3rd, and 5th buildings as that would form "0** _11_** " which is not allowed due to having two consecutive buildings of the same type.
Return thenumber of valid ways to select 3 buildings.
Input: s ="001101"Output: 6Explanation:
The following sets of indices selected are valid:-[0,2,4] from "_**0**_ 0** _1_** 1** _0_** 1" forms "010"-[0,3,4] from "_**0**_ 01 _**10**_ 1" forms "010"-[1,2,4] from "0 _**01**_ 1 _**0**_ 1" forms "010"-[1,3,4] from "0 _**0**_ 1 _**10**_ 1" forms "010"-[2,4,5] from "00 _**1**_ 1 _**01**_ " forms "101"-[3,4,5] from "001 _**101**_ " forms "101"No other selection is valid. Thus, there are 6 total ways.
We want to select 3 buildings such that no two consecutive selected buildings are of the same type. The only valid patterns are “010” and “101”. For each building in the middle, count the number of valid left and right buildings to form these patterns.
Precompute prefix sums for the number of ‘0’s and ‘1’s up to each index.
For each building at index i (as the middle building), if s[i] == ‘0’, count the number of ‘1’s to the left and right to form “101”; if s[i] == ‘1’, count the number of ‘0’s to the left and right to form “010”.
For each i, add left_count * right_count to the answer.
classSolution {
funnumberOfWays(s: String): Long {
val n = s.length
val pre0 = LongArray(n+1)
val pre1 = LongArray(n+1)
for (i in0 until n) {
pre0[i+1] = pre0[i] + if (s[i] =='0') 1else0 pre1[i+1] = pre1[i] + if (s[i] =='1') 1else0 }
var ans = 0Lfor (i in1 until n-1) {
if (s[i] =='0') {
ans += pre1[i] * (pre1[n] - pre1[i+1])
} else {
ans += pre0[i] * (pre0[n] - pre0[i+1])
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
classSolution:
defnumberOfWays(self, s: str) -> int:
n = len(s)
pre0 = [0]*(n+1)
pre1 = [0]*(n+1)
for i in range(n):
pre0[i+1] = pre0[i] + (s[i] =='0')
pre1[i+1] = pre1[i] + (s[i] =='1')
ans =0for i in range(1, n-1):
if s[i] =='0':
ans += pre1[i] * (pre1[n] - pre1[i+1])
else:
ans += pre0[i] * (pre0[n] - pre0[i+1])
return ans