1870. number of substrings with all zeroes
Given a string str containing only0 or 1, please return the number of substrings that are consist of 0 .
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
Notice
1<=|str|<=30000
解法1:
把每段的0...0都找出来,得到range_len。记得每个range的substrings的个数是range_len * (range_len + 1) / 2。
class Solution {
public:
/**
* @param str: the string
* @return: the number of substrings
*/
int stringCount(string &str) {
int len = str.size();
int range_len = 0, result = 0;
for (int i = 0; i < len; ++i) {
if (str[i] == '0') {
range_len++;
} else {
result += range_len * (range_len + 1) / 2;
range_len = 0;
}
}
if (range_len > 0) result += range_len * (range_len + 1) / 2;
return result;
}
};
解法2:
采用同向双指针,i是左指针,j是右指针。i指向0,j从i开始,遍历连续的0, 每个0会累加一个j-i+1。当j移到非0字符时,就不会累加0,而且j也不会移动。此时j要依靠j=max(i,j)来移动。不太好写。不如上面的方法好。
class Solution {
public:
/**
* @param str: the string
* @return: the number of substrings
*/
int stringCount(string &str) {
int len = str.size();
int i = 0, j = 0;
int res = 0;
for (i = 0; i < len; i++) {
if (str[i] != '0') continue;
j = max(i, j);
while(j < len && str[j] == '0') {
res += j - i + 1;
j++;
}
}
return res;
}
};
本文介绍了一种高效算法,用于计算字符串中所有由0组成的子串数量。通过两种方法实现:一是遍历并累计范围长度;二是使用同向双指针技术。这两种方法均能有效解决该问题。
304

被折叠的 条评论
为什么被折叠?



