696计数二进制子串

class Solution:
# 自己写的,超时。
def countBinarySubstrings1(self, s: str) -> int:
# 定义一个变量,用来存放数量
self.num = 0
# 字符串小于二的时候就直接返回零。
if len(s) < 2:
return self.num
# 然后挨着遍历。
for index in range(len(s)):
# 定义num1统计连续出现的字符个数
num1,index1 = 0,index
while index1 < len(s) and s[index1] == s[index]:
index1 += 1
num1 += 1
index2 = index1
# num2同理
num2 = 0
while index2 < len(s) and s[index2] == s[index1] and num2 < num1:
index2 += 1
num2 += 1
# 最后比较是否相同
if num2 == num1:
self.num += 1
return self.num
# 参考大佬的代码。
def countBinarySubstrings(self, s: str) -> int:
# 定义变量用来存放最后的数量
self.num = 0
index1 = 0
count = [1]
if len(s) < 2:
return self.num
# 首先统计相同的0和1连续出现的频数
for index2 in range(1,len(s)):
if s[index2] == s[index2 - 1]:
count[index1] += 1
else:
count.append(1)
index1 += 1
# 然后统计两个之间的最小值
for index in range(1,len(count)):
self.num += min(count[index],count[index - 1])
return self.num



A = Solution()
A.countBinarySubstrings("00110011")
A.countBinarySubstrings("10101")






原文地址:https://www.cnblogs.com/cong12586/p/13471352.html