Replies: 2 comments
-
Optimized Solution using
|
Beta Was this translation helpful? Give feedback.
0 replies
-
Manual Efficient Approach using Two PointersThis approach avoids excessive memory usage caused by multiple string replacements. <?php
function removeOccurrences($s, $part) {
$stack = "";
$partLen = strlen($part);
for ($i = 0, $n = strlen($s); $i < $n; $i++) {
$stack .= $s[$i];
// If the last part matches the substring, remove it
if (strlen($stack) >= $partLen && substr($stack, -$partLen) === $part) {
$stack = substr($stack, 0, -$partLen);
}
}
return $stack;
}
// Example Cases
echo removeOccurrences("daabcbaabcbc", "abc") . "\n"; // Output: "dab"
echo removeOccurrences("axxxxyyyyb", "xy") . "\n"; // Output: "ab"
?> ✅ Time Complexity: |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Subsequent calls to strpos could use lastpos-partlen+1 as an offset.
Beta Was this translation helpful? Give feedback.
All reactions