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 = “001101”, we cannot select the 1st, 3rd, and 5th 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.
Example 1:
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.
Example 2:
Input: s = “11100”
Output: 0
Explanation: It can be shown that there are no valid selections.
Constraints:
- 3 <= s.length <= 105
- s[i] is either ‘0’ or ‘1’.
遍历整条街, 如果 s[i] == 1, 那可能的组合是 s[0…i]中所有的 0 和 s[i+1…]中所有的 0 与 s[i]的组合, s[i] == 0 的情况与此相同, 只不过是 s[0…i]中所有的 1 和 s[i+1…]中所有的 1 与 s[i]的组合。我们现在要做的只是提前把每个 s[i]左边的 0 和 1 以及右边的 0 和 1 的数量都统计出来。
impl Solution {
pub fn number_of_ways(s: String) -> i64 {
// 统计每个元素左侧的0和1
let left: Vec<(i64, i64)> = s
.chars()
.scan((0, 0), |(zeros, ones), c| {
let curr_zeros = *zeros;
let curr_ones = *ones;
if c == '0' {
*zeros += 1;
} else {
*ones += 1;
}
Some((curr_zeros, curr_ones))
})
.collect();
// 统计每个元素右侧的0和1
let mut right: Vec<(i64, i64)> = s
.chars()
.rev()
.scan((0, 0), |(zeros, ones), c| {
let curr_zeros = *zeros;
let curr_ones = *ones;
if c == '0' {
*zeros += 1;
} else {
*ones += 1;
}
Some((curr_zeros, curr_ones))
})
.collect();
right.reverse();
let mut ans = 0;
for (i, c) in s.chars().enumerate() {
// 如果是0则用左侧的1的数量乘以右侧1的数量
if c == '0' {
ans += left[i].1 * right[i].1;
continue;
}
// 如果是1则用左侧的0的数量乘以右侧0的数量
ans += left[i].0 * right[i].0;
}
ans
}
}

给定一个二进制字符串s,代表街道上建筑物的类型,其中0表示办公室,1表示餐厅。要从街道中选择3栋建筑进行随机检查,但不能连续选择相同类型的建筑。例如,s='001101',不能选1st, 3rd, 5th。返回所有合法的选择方式数量。题目提供了两个例子说明如何计算。解决方案包括遍历字符串并统计每个位置前后不同类型的建筑数量。"
105165204,9032773,Linux操作系统中的进程管理与调度,"['操作系统', 'Linux', '进程管理', '调度算法', '多任务']
704

被折叠的 条评论
为什么被折叠?



