[LeetCode] 1513. Number of Substrings With Only 1s

Given a binary string s, return the number of substrings with all characters 1's. Since the answer may be too large, return it modulo 109 + 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.

Example 2:

Input: s = "101"
Output: 2
Explanation: Substring "1" is shown 2 times in s.

Example 3:

Input: s = "111111"
Output: 21
Explanation: Each substring contains only 1's characters.

Constraints:

  • 1 <= s.length <= 105
  • s[i] is either '0' or '1'.

仅含 1 的子串数。

给你一个二进制字符串 s(仅由 '0' 和 '1' 组成的字符串)。

返回所有字符都为 1 的子字符串的数目。

由于答案可能很大,请你将它对 10^9 + 7 取模后返回。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-substrings-with-only-1s
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题意是给一个字符串表示的数字,请你返回这个字符串里面有多少个由 1 组成的子串,同时需要把这个结果 % 10^9 + 7。子串有长有短,例子应该很清楚地解释了子串的数量是如何计算的了。

思路是 sliding window 滑动窗口。设前指针为 i,后指针为 j。前指针 i 一直往后走扫描 input 字符串,在遇到 0 或者遇到字符串末尾的时候停下来,开始结算,结算方式是(i - j) * (i - j + 1) / 2。结算完之后,将j指针移动到 i + 1 的位置上。关于这个结算方式,(i - j) * (i - j + 1) / 2,这其实就是等差数列求和公式,首项是 1,末项的下标是 i - j。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int numSub(String s) {
 3         long res = 0;
 4         for (long i = 0, j = 0; i <= s.length(); i++) {
 5             if (i == s.length() || s.charAt((int) i) == '0') {
 6                 res = (res + (i - j) * (i - j + 1) / 2) % 1000000007;
 7                 j = i + 1;
 8             }
 9         }
10         return (int) res;
11     }
12 }

 

或者直接沿用 1180 题的做法,等差数列求和公式。注意这道题的数据范围,变量 res 和变量 count 都需要设置成 long 型以避免溢出。

时间O(n)

空间O(1)

Java实现

 1 class Solution {
 2     public int numSub(String s) {
 3         int MOD = (int) Math.pow(10, 9) + 7;
 4         long res = 0;
 5         long count = 0;
 6         for (int i = 0; i < s.length(); i++) {
 7             char cur = s.charAt(i);
 8             if (cur == '1') {
 9                 count++;
10             } else {
11                 res += (1 + count) * count / 2;
12                 res %= MOD;
13                 count = 0;
14             }
15         }
16         res += (1 + count) * count / 2;
17         return (int) (res % MOD);
18     }
19 }

 

相关题目

1180. Count Substrings with Only One Distinct Letter - 统计连续出现的相同字母

1513. Number of Substrings With Only 1s - 统计连续出现的1

1759. Count Number of Homogenous Substrings

LeetCode 题目总结

posted @ 2020-07-13 08:03  CNoodle  阅读(293)  评论(0编辑  收藏  举报