1358. Number of Substrings Containing All Three Characters #1418
-
Topics: Given a string Return the number of substrings containing at least one occurrence of all these characters a, b and c. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of substrings in a given string that contain all three characters 'a', 'b', and 'c'. The solution should efficiently handle strings up to a length of 50,000 characters. ApproachThe approach involves using a sliding window technique combined with tracking the last occurrence of each character ('a', 'b', and 'c'). The key insight is that for each position in the string, we can determine the earliest position where all three characters have appeared. This allows us to count all valid substrings ending at the current position efficiently.
Let's implement this solution in PHP: 1358. Number of Substrings Containing All Three Characters <?php
/**
* @param String $s
* @return Integer
*/
function numberOfSubstrings($s) {
$last_a = -1;
$last_b = -1;
$last_c = -1;
$total = 0;
$n = strlen($s);
for ($j = 0; $j < $n; $j++) {
$char = $s[$j];
if ($char == 'a') {
$last_a = $j;
} elseif ($char == 'b') {
$last_b = $j;
} else {
$last_c = $j;
}
if ($last_a != -1 && $last_b != -1 && $last_c != -1) {
$min_last = min($last_a, $last_b, $last_c);
$total += ($min_last + 1);
}
}
return $total;
}
// Test cases
echo numberOfSubstrings("abcabc") . "\n"; // Output: 10
echo numberOfSubstrings("aaacb") . "\n"; // Output: 3
echo numberOfSubstrings("abc") . "\n"; // Output: 1
?> Explanation:
This approach ensures that each character is processed exactly once, leading to an O(n) time complexity, which is efficient for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to count the number of substrings in a given string that contain all three characters 'a', 'b', and 'c'. The solution should efficiently handle strings up to a length of 50,000 characters.
Approach
The approach involves using a sliding window technique combined with tracking the last occurrence of each character ('a', 'b', and 'c'). The key insight is that for each position in the string, we can determine the earliest position where all three characters have appeared. This allows us to count all valid substrings ending at the current position efficiently.