# 696. Count Binary Substrings 计数二进制子串

@TOC

## # 题目描述

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.

Substrings that occur multiple times are counted the number of times they occur.

Example 1:
Input: "00110011"
Output: 6
Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01".

Notice that some of these substrings repeat and are counted the number of times they occur.

Also, "00110011" is not a valid substring because all the 0's (and 1's) are not grouped together.
Example 2:
Input: "10101"
Output: 4
Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.

Note:

1. s.length will be between 1 and 50,000.
2. s will only consist of "0" or "1" characters.

## # 解题方法

### # 方法一：暴力解法（TLE）

class Solution(object):
def countBinarySubstrings(self, s):
"""
:type s: str
:rtype: int
"""
N = len(s)
res = 0
for i in range(N):
c1, c0 = 0, 0
if s[i] == "1":
c1 = 1
else:
c0 = 1
for j in range(i + 1, N):
if s[j] == "1":
c1 += 1
else:
c0 += 1
if c0 == c1:
res += 1
break
return res

### # 方法二：连续子串计算

class Solution(object):
def countBinarySubstrings(self, s):
"""
:type s: str
:rtype: int
"""
N = len(s)
curlen = 1
res = []
for i in range(1, N):
if s[i] == s[i - 1]:
curlen += 1
else:
res.append(curlen)
curlen = 1
res.append(curlen)
return sum(min(x, y) for x, y in zip(res[:-1], res[1:]))

class Solution(object):
def countBinarySubstrings(self, s):
"""
:type s: str
:rtype: int
"""
s = map(len, s.replace('01','0 1').replace('10','1 0').split())
return sum(min(i, j) for i,j in zip(s, s[1:]))

## # 日期

2018 年 1 月 27 日 2018 年 11 月 10 日 —— 欢度光棍节