本文主要是介绍Linecode 1870 · Number of Substrings with All Zeroes [Python],希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
每一段连续的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 = 0p2 = 0res = 0while p1 < len(string):if string[p1] == '0':p2 = p1while p2 < len(string) and string[p2] != '1':p2 += 1length = p2 - p1res += self.cals(length)p1 = p2 + 1else:p1 += 1return resdef cals(self, n):res = 0while n != 0:res += nn -= 1return 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
这篇关于Linecode 1870 · Number of Substrings with All Zeroes [Python]的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!