LeetCode 题解工作台

仅含 1 的子串数

给你一个二进制字符串 s (仅由 '0' 和 '1' 组成的字符串)。 返回所有字符都为 1 的子字符串的数目。 由于答案可能很大,请你将它对 10^9 + 7 取模后返回。 示例 1: 输入: s = "0110111" 输出 :9 解释: 共有 9 个子字符串仅由 '1' 组成 "1" -> 5…

category

2

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 数学·string

bolt

答案摘要

我们遍历字符串 ,用一个变量 记录当前连续的 1 的个数,用变量 记录答案。当遍历到字符 时,如果 $s[i] = 0$,则 置 0,否则 自增 1,然后 自增 ,并对 $10^9 + 7$ 取模。 遍历结束,返回 即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个二进制字符串 s(仅由 '0' 和 '1' 组成的字符串)。

返回所有字符都为 1 的子字符串的数目。

由于答案可能很大,请你将它对 10^9 + 7 取模后返回。

 

示例 1:

输入:s = "0110111"
输出:9
解释:共有 9 个子字符串仅由 '1' 组成
"1" -> 5 次
"11" -> 3 次
"111" -> 1 次

示例 2:

输入:s = "101"
输出:2
解释:子字符串 "1" 在 s 中共出现 2 次

示例 3:

输入:s = "111111"
输出:21
解释:每个子字符串都仅由 '1' 组成

示例 4:

输入:s = "000"
输出:0

 

提示:

  • s[i] == '0's[i] == '1'
  • 1 <= s.length <= 10^5
lightbulb

解题思路

方法一:遍历计数

我们遍历字符串 ss,用一个变量 cur\textit{cur} 记录当前连续的 1 的个数,用变量 ans\textit{ans} 记录答案。当遍历到字符 s[i]s[i] 时,如果 s[i]=0s[i] = 0,则 cur\textit{cur} 置 0,否则 cur\textit{cur} 自增 1,然后 ans\textit{ans} 自增 cur\textit{cur},并对 109+710^9 + 7 取模。

遍历结束,返回 ans\textit{ans} 即可。

时间复杂度 O(n)O(n),其中 nn 为字符串 ss 的长度。空间复杂度 O(1)O(1)

相似题目:

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def numSub(self, s: str) -> int:
        mod = 10**9 + 7
        ans = cur = 0
        for c in s:
            if c == "0":
                cur = 0
            else:
                cur += 1
                ans = (ans + cur) % mod
        return ans
speed

复杂度分析

指标
时间complexity is O(n) because the string is traversed once. Space complexity is O(1) since only counters and the final sum are maintained, independent of string length.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Check if the candidate recognizes the arithmetic series pattern in consecutive 1s.

  • question_mark

    Watch for correct handling of large results with modulo operations.

  • question_mark

    Assess whether the candidate optimizes by computing contributions in one pass instead of generating substrings.

warning

常见陷阱

外企场景
  • error

    Attempting to generate all substrings explicitly, which causes timeouts for large strings.

  • error

    Forgetting to reset the consecutive 1s counter after a 0, leading to incorrect sums.

  • error

    Neglecting to apply modulo 10^9 + 7, risking overflow for long sequences of 1s.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Count substrings with only 0s instead of 1s, requiring minimal code adjustment.

  • arrow_right_alt

    Calculate substrings of exactly k consecutive 1s, modifying the arithmetic sum approach.

  • arrow_right_alt

    Extend to 3-character strings and count substrings where all characters are identical.

help

常见问题

外企场景

仅含 1 的子串数题解:数学·string | LeetCode #1513 中等