Given a binary string s
(a string consisting only of '0' and '1's).
Return the number of substrings with all characters 1's.
Since the answer may be too large, return it modulo 10^9 + 7.
Example 1:
Input: s = "0110111" Output: 9 Explanation: There are 9 substring in total with only 1's characters. "1" -> 5 times. "11" -> 3 times. "111" -> 1 time.
思路1:统计有多少个连续的1,然后根据大小长度,频率记录下来,然后每个大小,是一个count,最后加起来就是答案;tricky的是最后一个连续的1,i要单独判断一下,如果是1,那么hashmap还要加入最后一个count;
class Solution {
public int numSub(String s) {
int MOD = 1000000007;
HashMap<Integer, Integer> hashmap = new HashMap<>();
char[] ss = s.toCharArray();
int count = 0;
int i = 0;
for(; i < ss.length; i++) {
if(ss[i] == '1') {
count++;
} else {
hashmap.put(count, hashmap.getOrDefault(count, 0) + 1);
count = 0;
}
}
if(ss[n - 1] == '1') {
hashmap.put(count, hashmap.getOrDefault(count, 0) + 1);
}
int res = 0;
for(Integer key: hashmap.keySet()) {
res = res % MOD + ( getSum(key, MOD) % MOD * hashmap.get(key) % MOD ) % MOD;
}
return res;
}
private int getSum(int len, int MOD) {
int res = 0;
for(int i = len; i >= 1; i--) {
res = res % MOD + i % MOD;
}
return res;
}
}
思路2: dp, 0110111, 0120123,dp[i] 表示的物理意义就是到目前为止,1的个数;
class Solution {
public int numSub(String s) {
int n = s.length();
int[] dp = new int[n + 1];
dp[0] = 0;
int MOD = 1000000007;
int sum = 0;
for(int i = 1; i <= n; i++) {
if(s.charAt(i - 1) == '1') {
dp[i] = dp[i - 1] + 1;
} else {
dp[i] = 0;
}
sum = sum % MOD + dp[i] % MOD;
}
return sum % MOD;
}
}