标签:ati span nts bin block HERE return i++ 应该
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的位置上。
时间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 }
[LeetCode] 1513. Number of Substrings With Only 1s
标签:ati span nts bin block HERE return i++ 应该
原文地址:https://www.cnblogs.com/cnoodle/p/13291384.html