作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/baseball-game/description/

题目描述

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.

题目大意

一个字符串由01组成,现在需要寻找满足连续子字符串中01个数相等的子字符串的个数。如果在不同位置出现的子字符串,不要去重计数。

解题方法

方法一:暴力解法(TLE)

看了s的长度那么大,估计暴力解法会超时,果然就超时了。但是做法很简单,只需要从每个位置开始向后数,数到0的个数和1的个数相等时候停止就好了。每次不需要遍历到结尾,所以最坏时间复杂度是O(N^2),最优时间复杂度是O(N)。但是没有通过。

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

方法二:连续子串计算

首先,数一下,连续的0,1的个数有多少,构成一个数组。比如,“0110001111”的连续0和1的个数是[1, 2, 3, 4].

然后,我们想求得0和1的个数相等的子串,所以需要进行一个交错,找出相邻的两个个数的最小值就好了。比如“0001111”, 结果是min(3, 4) = 3, 即,("01", "0011", "000111")

有什么道理呢?因为我们求得字符串出现的数组,它的每个位置一定是0,1交错的子字符串长度。否则相邻的0或者1会拼成更长的长度。所以我们最后求交错的最小值,就是得到了相邻字符串的0和1相等的长度。

根据上面的思路,可以写出这个代码:

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 日 —— 欢度光棍节

【LeetCode】696. Count Binary Substrings 解题报告(Python)的更多相关文章

  1. LeetCode 696 Count Binary Substrings 解题报告

    题目要求 Give a string s, count the number of non-empty (contiguous) substrings that have the same numbe ...

  2. LeetCode 696. Count Binary Substrings

    Give a string s, count the number of non-empty (contiguous) substrings that have the same number of ...

  3. 【LeetCode】647. Palindromic Substrings 解题报告(Python)

    [LeetCode]647. Palindromic Substrings 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/problems/p ...

  4. 696. Count Binary Substrings - LeetCode

    Question 696. Count Binary Substrings Example1 Input: "00110011" Output: 6 Explanation: Th ...

  5. 【Leetcode_easy】696. Count Binary Substrings

    problem 696. Count Binary Substrings 题意:具有相同个数的1和0的连续子串的数目: solution1:还不是特别理解... 遍历元数组,如果是第一个数字,那么对应 ...

  6. [LeetCode&Python] Problem 696. Count Binary Substrings

    Give a string s, count the number of non-empty (contiguous) substrings that have the same number of ...

  7. 【LeetCode】647. Palindromic Substrings 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:暴力循环 方法二:固定起点向后找 方法三:动 ...

  8. 【LeetCode】401. Binary Watch 解题报告(Java & Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 java解法 Python解法 日期 [LeetCo ...

  9. 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...

随机推荐

  1. MybatisPlus使用Wrapper实现查询功能

    Wrapper---条件查询器 :使用它可以实现很多复杂的查询 几个案例 环境: 参照博客:MybatisPlus入门程序 1.条件查询 1.1 查询name不为空的用户,并且邮箱不为空的用户,年龄大 ...

  2. CSS3单行文本两端对齐

    CSS3实现单行文本两端对齐 p { height: 24px; text-align: justify; text-last-align: justify; } p::after { display ...

  3. 并发 并行 进程 线程 协程 异步I/O python async

    一些草率不精确的观点: 并发: 一起发生,occurence: sth that happens. 并行: 同时处理. parallel lines: 平行线.thread.join()之前是啥?落霞 ...

  4. aboard, abolish

    aboard board做动词有上车/船/飞机的意思,boarding就是正在上.board做名词有板的意思,车厢地板的板. a是个词根,有三种意思:1. 以某种状态或方式,如: ablaze, af ...

  5. A Child's History of England.43

    PART THE SECOND When the King heard how Thomas à Becket had lost his life in Canterbury Cathedral, t ...

  6. Mybatis相关知识点(一)

    MyBatis入门 (一)介绍 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code, ...

  7. Scala(七)【异常处理】

    目录 一.try-catch-finally 二.Try(表达式).getOrElse(异常出现返回的默认值) 三. 直接抛出异常 一.try-catch-finally 使用场景:在获取外部链接的时 ...

  8. 大数据学习day23-----spark06--------1. Spark执行流程(知识补充:RDD的依赖关系)2. Repartition和coalesce算子的区别 3.触发多次actions时,速度不一样 4. RDD的深入理解(错误例子,RDD数据是如何获取的)5 购物的相关计算

    1. Spark执行流程 知识补充:RDD的依赖关系 RDD的依赖关系分为两类:窄依赖(Narrow Dependency)和宽依赖(Shuffle Dependency) (1)窄依赖 窄依赖指的是 ...

  9. ES6必知,箭头函数与普通函数的区别。

    1. 箭头函数没有prototype(原型),所以箭头函数本身没有this let a = () =>{}; console.log(a.prototype); // undefined 2. ...

  10. D3基础入门四-事件处理

    6.5.0版 .on("mouseover", function(e,d) e: {"isTrusted":true} 第二个参考才是数据,但这在不同的环境可能 ...