Suppose we have a binary string s. We have to find the number of substrings that contain only "1"s. If the answer is too large, mod the result by 10^9+7.
So, if the input is like s = "100111", then the output will be 7, because the substrings containing only "1"s are ["1", "1", "1", "1", "11", "11" and "111"]
To solve this, we will follow these steps −
- a := 0
- count := 0
- for i in range 0 to size of s - 1, do
- if s[i] is same as "0", then
- a := 0
- otherwise,
- a := a + 1
- count := count + a
- if s[i] is same as "0", then
- return count
Example
Let us see the following implementation to get better understanding −
def solve(s): a = 0 count = 0 for i in range(len(s)): if s[i] == "0": a = 0 else: a += 1 count += a return count s = "100111" print(solve(s))
Input
"100111"
Output
7