|
| 1 | +/** |
| 2 | + * [0696] Count Binary Substrings |
| 3 | + * |
| 4 | + * Give a binary string s, return the number of non-empty substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. |
| 5 | + * Substrings that occur multiple times are counted the number of times they occur. |
| 6 | + * |
| 7 | + * Example 1: |
| 8 | + * |
| 9 | + * Input: s = "00110011" |
| 10 | + * Output: 6 |
| 11 | + * Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01". |
| 12 | + * Notice that some of these substrings repeat and are counted the number of times they occur. |
| 13 | + * Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together. |
| 14 | + * |
| 15 | + * Example 2: |
| 16 | + * |
| 17 | + * Input: s = "10101" |
| 18 | + * Output: 4 |
| 19 | + * Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's. |
| 20 | + * |
| 21 | + * |
| 22 | + * Constraints: |
| 23 | + * |
| 24 | + * 1 <= s.length <= 10^5 |
| 25 | + * s[i] is either '0' or '1'. |
| 26 | + * |
| 27 | + */ |
| 28 | +pub struct Solution {} |
| 29 | + |
| 30 | +// problem: https://leetcode.com/problems/count-binary-substrings/ |
| 31 | +// discuss: https://leetcode.com/problems/count-binary-substrings/discuss/?currentPage=1&orderBy=most_votes&query= |
| 32 | + |
| 33 | +// submission codes start here |
| 34 | + |
| 35 | +impl Solution { |
| 36 | + pub fn count_binary_substrings(s: String) -> i32 { |
| 37 | + s.as_bytes() |
| 38 | + .windows(2) |
| 39 | + .fold(vec![1], |mut v, w| { |
| 40 | + if w[0] == w[1] { |
| 41 | + *v.last_mut().unwrap() += 1; |
| 42 | + } else { |
| 43 | + v.push(1); |
| 44 | + } |
| 45 | + v |
| 46 | + }) |
| 47 | + .windows(2) |
| 48 | + .map(|w| w[0].min(w[1])) |
| 49 | + .sum() |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +// submission codes end |
| 54 | + |
| 55 | +#[cfg(test)] |
| 56 | +mod tests { |
| 57 | + use super::*; |
| 58 | + |
| 59 | + #[test] |
| 60 | + fn test_0696_example_1() { |
| 61 | + let s = "00110011".to_string(); |
| 62 | + let result = 6; |
| 63 | + |
| 64 | + assert_eq!(Solution::count_binary_substrings(s), result); |
| 65 | + } |
| 66 | + |
| 67 | + #[test] |
| 68 | + fn test_0696_example_2() { |
| 69 | + let s = "10101".to_string(); |
| 70 | + let result = 4; |
| 71 | + |
| 72 | + assert_eq!(Solution::count_binary_substrings(s), result); |
| 73 | + } |
| 74 | +} |
0 commit comments