1910. Remove All Occurrences of a Substring #1300
-
Topics: Given two strings
Return A substring is a contiguous sequence of characters in a string. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to repeatedly remove all occurrences of a substring Approach
This approach ensures that after each removal, we check the modified string again for new occurrences, which might have formed due to the previous removal. This is necessary because removing a substring can create a new occurrence of Let's implement this solution in PHP: 1910. Remove All Occurrences of a Substring <?php
function removeOccurrences($s, $part) {
$partLength = strlen($part);
if ($partLength == 0) {
return $s;
}
while (true) {
$pos = strpos($s, $part);
if ($pos === false) {
break;
}
$s = substr($s, 0, $pos) . substr($s, $pos + $partLength);
}
return $s;
}
// Example 1
$s1 = "daabcbaabcbc";
$part1 = "abc";
echo "Output 1: " . removeOccurrences($s1, $part1) . PHP_EOL; // Output: "dab"
// Example 2
$s2 = "axxxxyyyyb";
$part2 = "xy";
echo "Output 2: " . removeOccurrences($s2, $part2) . PHP_EOL; // Output: "ab"
?> Explanation:
This approach efficiently handles the problem by leveraging PHP's built-in string functions to find and remove substrings iteratively, ensuring that all possible occurrences (including those formed due to previous removals) are addressed. The time complexity is O(n^2) in the worst case, which is manageable given the problem constraints. |
Beta Was this translation helpful? Give feedback.
We need to repeatedly remove all occurrences of a substring
part
from the strings
until no more occurrences exist. Each time we remove the leftmost occurrence ofpart
, we need to check the resulting string again for new occurrences that might have formed due to the removal.Approach
part
in the strings
.part
are found in the string.This approach ensures that after each removal, we che…