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

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.

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.

Example 4:

Input: s = "000"
Output: 0

Constraints:

  • s[i] == '0' or s[i] == '1'
  • 1 <= s.length <= 10^5

题意是给一个字符串表示的数字,请你返回这个字符串里面有多少个由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,这是一个数学结论,用来统计多个数字之间有多少种排列组合。

时间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题的做法,还是用一个count表示连续出现的1的个数,并且累加到res中。记得res需要% 1000000007。

时间O(n)

空间O(n) - charArray

Java实现

 1 class Solution {
 2     public int numSub(String s) {
 3         int count = 0;
 4         int res = 0;
 5         for (char c : s.toCharArray()) {
 6             if (c == '1') {
 7                 count++;
 8                 res += count;
 9                 res %= 1000000007;
10             } else {
11                 count = 0;
12             }
13         }
14         return res;
15     }
16 }

相关题目

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

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

sliding window相关题目

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/13291384.html