Count Binary Substrings LeetCode solution in Python

1
# Runtime: 133 ms (Top 63.3%) | Memory: 16.65 MB (Top 94.0%)
2

3

4
class Solution:
5
def countBinarySubstrings(self, s: str) -> int:
6

7
# previous continuous occurrence, current continuous occurrence
8
pre_cont_occ, cur_cont_occ = 0, 1
9

10
# counter for binary substrings with equal 0s and 1s
11
counter = 0
12

13
# scan each character pair in s
14
for idx in range(1, len(s)):
15

16
if s[idx] == s[idx - 1]:
17

18
# update current continuous occurrence
19
cur_cont_occ += 1
20

21
else:
22
# update counter of binary substrings between prevous character group and current character group
23
counter += min(pre_cont_occ, cur_cont_occ)
24

25
# update previous as current's continuous occurrence
26
pre_cont_occ = cur_cont_occ
27

28
# reset current continuous occurrence to 1
29
cur_cont_occ = 1
30

31
# update for last time
32
counter += min(pre_cont_occ, cur_cont_occ)
33

34
return counter

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0