leetcode

Leetcode Solutions (0x6A73)
git clone https://git.pngu.org/leetcode
Log | Files | Refs | Submodules | README

commit 758bb05572b1e5948c3a9b9ce4413ffede87362b
parent ef565e321f29ebb749d8fdad74a0f7d7105ddee0
Author: Jack Sangdahl <jack@pngu.org>
Date:   Wed, 18 Feb 2026 20:41:44 -0700

696. count binary substrings

Diffstat:
Acount_binary_substr.c | 33+++++++++++++++++++++++++++++++++
Acount_binary_substr.py | 26++++++++++++++++++++++++++
2 files changed, 59 insertions(+), 0 deletions(-)

diff --git a/count_binary_substr.c b/count_binary_substr.c @@ -0,0 +1,33 @@ +// 696. Count Binary Substrings +#include "leetcode.h" + +/* + * given 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 group consecutively. substrings that occur multiple times are + * counted the number of times they occur. + */ + +int countBinarySubstrings(char *s) { + int curr = 1, pre = 0, ans = 0, n = strlen(s); + for (int i = 1; i < n; i++) { + if (s[i] == s[i - 1]) + curr++; + else { + ans += fmin(curr, pre); + pre = curr; + curr = 1; + } + } + return ans + fmin(curr, pre); +} + +int main() { + char *s1 = "00110011", *s2 = "10101"; + int r1 = countBinarySubstrings(s1); + int r2 = countBinarySubstrings(s2); + printf("%d\n", r1); // expect: 6 + assert(r1 == 6); + printf("%d\n", r2); // expect: 4 + assert(r2 == 4); +} diff --git a/count_binary_substr.py b/count_binary_substr.py @@ -0,0 +1,26 @@ +# 696. Count Binary Substrings + +""" +given 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 group consecutively. substrings that occur multiple times are +counted the number of times they occur. +""" + + +class Solution: + def countBinarySubstrings(self, s: str) -> int: + curr, prev, ans = 1, 0, 0 + for i in range(1, len(s)): + if s[i] == s[i - 1]: + curr += 1 + else: + ans += min(curr, prev) + prev, curr = curr, 1 + return ans + min(curr, prev) + + +if __name__ == "__main__": + obj = Solution() + print(obj.countBinarySubstrings(s="00110011")) + print(obj.countBinarySubstrings(s="10101"))