问题描述:

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.

思路:

由于s中只有0或1,并且要组成对必须是相邻的0和1才可以,基于这点,只考虑相邻的0、1即可

数量如何确定呢?明显有多少个1,就需要配置多少个0,故相邻01组合最终能凑成多少对,看0和1谁的个数最少即可。

代码:

 class Solution:
def countBinarySubstrings(self, s: str) -> int:
s = list(map(len, s.replace('', '1 0').replace('', '0 1').split()))
return sum(min(i, j) for i, j in zip(s, s[1:]))

第一行代码,将01的字符串分组,每组仅仅包含0或仅仅包含1。同时计算每组中元素的个数

第二行代码,zip将相邻两个分组组合起来(每个分组中存储的是该分组元素个数),每个组合中较小的数字代表 该组组合能够拆成的符合条件的子串个数,然后将所有组合能够拆成的子串个数相加,得到的结果即是最终所有的个数

最新文章

  1. DOS:将某文件夹下面的所有某一类型文件名输出
  2. Redis安装配置与Jedis访问数据库
  3. 与你相遇好幸运,CentOS 7 x86_64使用Yum安装PostgreSQL
  4. iOS - UIAlertView
  5. urlrewrite 地址重写
  6. TCP通信三次握手的过程
  7. 一次服务器CPU占用率高的定位分析
  8. SqlServer:CTE函数处理递归(WITH语法)
  9. C# 6.0 (C# vNext) 的新功能:Exception-Handling Improvements
  10. 【原创】有关Buffer使用,让你的日志类库解决IO高并发写
  11. shell脚本进阶之条件测试与条件语句
  12. oracle 角色
  13. Java Socket通信以及可能出现的问题解决
  14. 1013团队Beta冲刺day7
  15. 用系统为centos6的主机,搭建PXE服务器,实现批量安装centos6,7系统
  16. apache-2.4.6 mod_bw-0.92 实现限速上传或下载
  17. Spring Boot:快速入门(二)
  18. JSTL_Format标记库
  19. node.js如何将远程的文件下载到本地、解压、读取
  20. sqlldr和sqludr使用笔记

热门文章

  1. ubuntu安装和使用git
  2. VMware 虚拟化编程(9) — VMware 虚拟机的快照
  3. 《上瘾 - 让用户养成使用习惯的四大产品逻辑》 - Nir Eyal, Ryan Hoover
  4. 《计算机程式设计》Week5 课堂笔记
  5. 双系统(win10+ubuntu)卸载Ubuntu系统
  6. 关于jdbc和数据库连接池的关系(不是封装的关系)
  7. sqluldr2 oracle直接导出数据为文本的小工具使用
  8. sql中的isnull
  9. [19/05/26-星期日] JavaScript_ 基本语法_运算符
  10. D-query SPOJ 树状数组+离线