Skip to content

Commit 2d4cf28

Browse files
authored
Create Count Binary Substrings.py
1 parent 6e9d679 commit 2d4cf28

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

Count Binary Substrings.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
'''
2+
Give a string s, count the number of non-empty (contiguous) 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.
3+
4+
Substrings that occur multiple times are counted the number of times they occur.
5+
6+
Example 1:
7+
Input: "00110011"
8+
Output: 6
9+
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".
10+
11+
Notice that some of these substrings repeat and are counted the number of times they occur.
12+
13+
Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.
14+
Example 2:
15+
Input: "10101"
16+
Output: 4
17+
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.
18+
Note:
19+
20+
s.length will be between 1 and 50,000.
21+
s will only consist of "0" or "1" characters.
22+
'''
23+
24+
class Solution(object):
25+
def countBinarySubstrings(self, s):
26+
"""
27+
:type s: str
28+
:rtype: int
29+
"""
30+
if len(s) < 2:
31+
return 0
32+
33+
res = 0
34+
prev = 0
35+
cur = 1
36+
for i in xrange(1, len(s)):
37+
if s[i] != s[i-1]:
38+
res += min(prev, cur)
39+
prev, cur = cur, 1
40+
else:
41+
cur += 1
42+
43+
res += min(prev, cur)
44+
return res

0 commit comments

Comments
 (0)