LeetCode 1513 Number of Substrings With Only 1s (Python)

Posted by 小明MaxMing on June 11, 2020

题目

Given a binary string s (a string consisting only of ‘0’ and ‘1’s).

Return the number of substrings with all characters 1’s.

Since the answer may be too large, return it modulo 10^9 + 7.

解题思路

长度为n的连续的1可以构成 n * (n + 1) / 2子串

代码

class Solution:
    def numSub(self, s: str) -> int:
        MOD = 1000000007
        res = ct = 0
        for c in s:
            if c == '0':
                res += (1 + ct) * ct // 2
                ct = 0
            else:
                ct += 1
        return (res + (1 + ct) * ct // 2) % MOD

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅