You are given a 0-indexed binary string s
which represents the types of buildings along a street where:
s[i] = '0'
denotes that theith
building is an office ands[i] = '1'
denotes that theith
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 = "001101"
, we cannot select the1st
,3rd
, and5th
buildings as that would form"011"
which is not allowed due to having two consecutive buildings of the same type.
Return the number of valid ways to select 3 buildings.
Input: s = "001101" Output: 6 Explanation: The following sets of indices selected are valid: - [0,2,4] from "001101" forms "010" - [0,3,4] from "001101" forms "010" - [1,2,4] from "001101" forms "010" - [1,3,4] from "001101" forms "010" - [2,4,5] from "001101" forms "101" - [3,4,5] from "001101" forms "101" No other selection is valid. Thus, there are 6 total ways.
Input: s = "11100" Output: 0 Explanation: It can be shown that there are no valid selections.
3 <= s.length <= 105
s[i]
is either'0'
or'1'
.
impl Solution {
pub fn number_of_ways(s: String) -> i64 {
let mut count0 = vec![0; s.len()];
let mut count1 = vec![0; s.len()];
for (i, building) in s.chars().enumerate() {
if i > 0 {
count0[i] = count0[i - 1];
count1[i] = count1[i - 1];
}
count0[i] += (building == '0') as i64;
count1[i] += (building == '1') as i64;
}
s.chars()
.enumerate()
.map(|(i, building)| match building {
'0' => count1[i] * (count1[s.len() - 1] - count1[i]),
_ => count0[i] * (count0[s.len() - 1] - count0[i]),
})
.sum()
}
}