Cover image for LeetCode daily problem P1513 Number of Substrings With Only 1s

LeetCode daily problem P1513 Number of Substrings With Only 1s

Words 126
Views
Visitors

Timeline

Timeline

2025-11-16

init

string

Problem:

Only one pass is needed.

1234567891011121314151617181920212223242526272829
#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 finds the first 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;	}};
Loading comments…