题目地址:
https://www.lintcode.com/problem/number-of-substrings-with-all-zeroes/description
给定一个 0 − 1 0-1 0−1字符串 s s s,求其只含 0 0 0的子串个数。
考虑一个长度为 l l l的只含 0 0 0的字符串,则其所有子串都满足条件。考虑其有多少个子串。首先,其长度为 1 1 1的子串有 l l l个,其长度大于 1 1 1的子串的个数,等价于在 1 , . . . , l 1,...,l 1,...,l中选取两个数的方式数,所以是 ( l 2 ) = l ( l − 1 ) 2 \tbinom{l}{2}=\frac{l(l-1)}{2} (2l)=2l(l−1);所以总共有 l + l ( l − 1 ) 2 = l ( l + 1 ) 2 l+\frac{l(l-1)}{2}=\frac{l(l+1)}{2} l+2l(l−1)=2l(l+1)个子串。
接着只需要将 s s s中的最长 0 0 0子串都截出来累加起来即可。代码如下:
public class Solution {
/**
* @param str: the string
* @return: the number of substrings
*/
public int stringCount(String str) {
// Write your code here.
int res = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
// 找到0了,则将以它开头的最长0子串截出来
if (ch == '0') {
int j = i + 1;
while (j < str.length() && str.charAt(j) == '0') {
j++;
}
// s[i, ..., j - 1]就是一个0子串,其子串个数是l(l + 1)/2
res += (j - i) * (j - i + 1) / 2;
// 将i移到0后面去
i = j;
}
}
return res;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。