时间轴

2025-11-16

init


题目:


经典的双指针题目,只需要一次遍历。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <string>

using std::string;

class Solution {
public:
int numSub(string s)
{
long res = 0, left = 0, right = 0;
long len;
int n = s.size();

while (left <= right && right < n) {
// left找到第一个1
while (left < n && s[left] != '1') {
left++;
}
right = left;
while (right < n && s[right] == '1') {
right++;
}
// [left, right)
len = right - left;
res += (len + 1) * len / 2 % 1000000007;
left = right;
}
return res;
}
};