1513. Number of Substrings With Only 1s #2428
-
|
Topics: Given a binary string Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to count all substrings that contain only '1's in a binary string. Approach:The key insight is that for a contiguous group of n '1's:
So we can:
Let's implement this solution in PHP: 1513. Number of Substrings With Only 1s <?php
/**
* @param String $s
* @return Integer
*/
function numSub($s) {
$mod = 1000000007;
$total = 0;
$currentCount = 0;
for ($i = 0; $i < strlen($s); $i++) {
if ($s[$i] == '1') {
$currentCount++;
} else {
// Calculate substrings for the current group of 1s
$total = ($total + (int)($currentCount * ($currentCount + 1) / 2)) % $mod;
$currentCount = 0;
}
}
// Don't forget the last group
$total = ($total + (int)($currentCount * ($currentCount + 1) / 2)) % $mod;
return $total;
}
// Test cases
echo numSub("0110111") . "\n"; // Output: 9
echo numSub("101") . "\n"; // Output: 2
echo numSub("111111") . "\n"; // Output: 21
?>Explanation:
Time Complexity: O(n) where n is the length of the string |
Beta Was this translation helpful? Give feedback.
We need to count all substrings that contain only '1's in a binary string.
Approach:
The key insight is that for a contiguous group of n '1's:
So we can:
Let's implement this solution in PHP: 1513. Number of Substrings With Only 1s