Remove All Occurrences of a Substring

medium stack string

Problem

You are given two strings s and part, both made of lowercase English letters. As long as s still contains part, delete the leftmost occurrence of part from s. Return whatever string is left when no occurrence remains.

The twist: deleting one occurrence can glue the characters on either side of the gap together and create a brand-new occurrence that was not there before.

Inputs = "daabcbaabcbc", part = "abc"
Output"dab"
Peel off "abc" three times: daabcbaabcbcdabaabcbcdababcdab.

def remove_occurrences(s, part):
    stack = []
    k = len(part)
    for ch in s:
        stack.append(ch)
        if len(stack) >= k and ''.join(stack[-k:]) == part:
            del stack[-k:]
    return ''.join(stack)
function removeOccurrences(s, part) {
  const stack = [];
  const k = part.length;
  for (const ch of s) {
    stack.push(ch);
    if (stack.length >= k && stack.slice(-k).join("") === part) {
      stack.length -= k;
    }
  }
  return stack.join("");
}
String removeOccurrences(String s, String part) {
    StringBuilder stack = new StringBuilder();
    int k = part.length();
    for (char ch : s.toCharArray()) {
        stack.append(ch);
        int n = stack.length();
        if (n >= k && stack.substring(n - k).equals(part)) {
            stack.delete(n - k, n);
        }
    }
    return stack.toString();
}
string removeOccurrences(string s, string part) {
    string stack;
    int k = part.size();
    for (char ch : s) {
        stack.push_back(ch);
        int n = stack.size();
        if (n >= k && stack.compare(n - k, k, part) == 0) {
            stack.erase(n - k);
        }
    }
    return stack;
}
Time: O(n · k) Space: O(n)