Skip to content

Commit 9d3b48e

Browse files
authored
Create count-binary-substrings.py
1 parent cb2bbb2 commit 9d3b48e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Python/count-binary-substrings.py

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Time: O(n)
2+
# Space: O(1)
3+
4+
# Give a string s, count the number of non-empty (contiguous) substrings
5+
# that have the same number of 0's and 1's, and all the 0's and all the 1's
6+
# in these substrings are grouped consecutively.
7+
#
8+
# Substrings that occur multiple times are counted the number of times they occur.
9+
#
10+
# Example 1:
11+
# Input: "00110011"
12+
# Output: 6
13+
# Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's:
14+
# "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+
# Example 2:
20+
# Input: "10101"
21+
# Output: 4
22+
# Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.
23+
#
24+
# Note:
25+
# s.length will be between 1 and 50,000.
26+
# s will only consist of "0" or "1" characters.
27+
28+
class Solution(object):
29+
def countBinarySubstrings(self, s):
30+
"""
31+
:type s: str
32+
:rtype: int
33+
"""
34+
result, prev, curr = 0, 0, 1
35+
for i in xrange(1, len(s)):
36+
if s[i-1] != s[i]:
37+
result += min(prev, curr)
38+
prev, curr = curr, 1
39+
else:
40+
curr += 1
41+
result += min(prev, curr)
42+
return result

0 commit comments

Comments
 (0)