一、题目描述


二、解题思路
解法一:双指针枚举(超时)
采用双指针来枚举所有可能的子串,并用step来记录子串的数量。
解法二:找规律
我们可以采用找规律来解决这个问题,长度为n全为'1'的字符串,有n(n+1)/2个全为'1'的子字符串,所以我们可以利用这个规律,一次遍历s,在过程中统计连续'1'的个数,实时计算仅含'1'的子串的数量。
三、代码实现
解法一:双指针枚举(超时)
cpp
class Solution {
public:
int numSub(string s) {
//双指针
int step=0;
for(int left=0;left!=s.size();left++)
for(int right=left;right!=s.size();right++){
if(s[right]=='1') step++;
else if(s[right]!='1') break;
}
return step;
}
};
解法二:找规律
cpp
class Solution {
public:
int numSub(string s) {
int ret=0;
int mod=1e9+7;
long long count_one=0;
for(int current=0;current!=s.size();current++){
if(s[current]=='1') count_one++;
else{
ret+=(count_one*(count_one+1)/2)%mod;
count_one=0;
}
}
//处理最后一段
ret+=(count_one*(count_one+1)/2)%mod;
return ret;
}
};