题目
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