|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 696. Count Binary Substrings |
| 5 | + * |
| 6 | + * Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, |
| 7 | + * and all the 0's and all the 1's in these substrings are grouped consecutively. |
| 8 | + * Substrings that occur multiple times are counted the number of times they occur. |
| 9 | +
|
| 10 | + Example 1: |
| 11 | +
|
| 12 | + Input: "00110011" |
| 13 | + Output: 6 |
| 14 | + Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01". |
| 15 | +
|
| 16 | + Notice that some of these substrings repeat and are counted the number of times they occur. |
| 17 | +
|
| 18 | + Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together. |
| 19 | +
|
| 20 | + Example 2: |
| 21 | +
|
| 22 | + Input: "10101" |
| 23 | + Output: 4 |
| 24 | + Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's. |
| 25 | +
|
| 26 | + Note: |
| 27 | + s.length will be between 1 and 50,000. |
| 28 | + s will only consist of "0" or "1" characters. |
| 29 | + */ |
| 30 | +public class _696 { |
| 31 | + public static class Solution1 { |
| 32 | + public int countBinarySubstrings(String s) { |
| 33 | + int n = s.length(); |
| 34 | + /**a[i][0] denotes from most left up to i (inclusive), how many consecutive 0's |
| 35 | + * a[i][1] denotes from most left up to i (inclusive), how many consecutive 1's*/ |
| 36 | + int[][] a = new int[n][2]; |
| 37 | + /**a[i][0] denotes from i (inclusive) to the most right, how many consecutive 0's |
| 38 | + * b[i][0] denotes from i (inclusive) to the most right, how many consecutive 1's*/ |
| 39 | + int[][] b = new int[n][2]; |
| 40 | + for (int i = 0; i < n; i++) { |
| 41 | + if (s.charAt(i) == '0') { |
| 42 | + a[i][0] = 1 + (i - 1 >= 0 ? a[i - 1][0] : 0); |
| 43 | + } else { |
| 44 | + a[i][1] = 1 + (i - 1 >= 0 ? a[i - 1][1] : 0); |
| 45 | + } |
| 46 | + } |
| 47 | + for (int i = n - 1; i >= 0; i--) { |
| 48 | + if (s.charAt(i) == '0') { |
| 49 | + b[i][0] = 1 + (i + 1 < n ? b[i + 1][0] : 0); |
| 50 | + } else { |
| 51 | + b[i][1] = 1 + (i + 1 < n ? b[i + 1][1] : 0); |
| 52 | + } |
| 53 | + |
| 54 | + } |
| 55 | + long ans = 0; |
| 56 | + for (int i = 0; i + 1 < n; i++) { |
| 57 | + ans += Math.min(a[i][0], b[i + 1][1]); |
| 58 | + ans += Math.min(a[i][1], b[i + 1][0]); |
| 59 | + } |
| 60 | + return (int) ans; |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments