每一段连续的0 有多少全0substring呢?观察计算可知是其长度N的连续加和至0,也就是N + N-1 + N-2 。。。。+ 1
class Solution:
"""
@param str: the string
@return: the number of substrings
"""
def stringCount(self, string):
# Write your code here.
p1 = 0
p2 = 0
res = 0
while p1 < len(string):
if string[p1] == '0':
p2 = p1
while p2 < len(string) and string[p2] != '1':
p2 += 1
length = p2 - p1
res += self.cals(length)
p1 = p2 + 1
else:
p1 += 1
return res
def cals(self, n):
res = 0
while n != 0:
res += n
n -= 1
return res
Algorithms
Medium
Accepted Rate
64%
DescriptionSolutionNotesDiscussLeaderboard
Description
Given a string str containing only 0 or 1, please return the number of substrings that consist of 0 .
1<=|str|<=30000
Example
Example 1:
Input:
“00010011”
Output:
9
Explanation:
There are 5 substrings of “0”,
There are 3 substrings of “00”,
There is 1 substring of “000”.
So return 9
Example 2:
Input:
“010010”
Output:
5