LeetCode · July 15, 2021

Remove All Occurrences of a Substring | LeetCode 1910 | Python | Solution

Click here to see the problem details.

Problem Overview

We will be given a string (s) and a substring (part). We have to remove all occurrences from the string based on the given substring. We will continue to remove until all the occurrences of the substring are removed. Each time we have to remove the leftmost occurrence from the given string.

After that, we will return the string.

The problem is simple. I am going to make this complicated in the next portion. ๐Ÿ˜Ž

Coding Part

We will use replace method to solve this problem. If we use this method simply, it will remove all substring occurrences from the string. But then there is a chance that the remaining string might create a new substring that is similar to the given one. Let’s see what happens if we apply this to one of the example’s input.

s = 'daabcbaabcbc'
part = 'abc'
res = s.replace(part, '') # 'da{abc}ba{abc}bc'
print(res) # 'dababc' new substring is created 'dab{abc}'

Generally, replace method replaces all the occurrences from a string. But we can replace only the first occurrence from a string. For that, we have to put 1 as the third parameter of the method. So we will run a while loop with the condition: part in s. And each time, we will remove one occurrence, and the remaining string will store into the same variable.

After the loop finishes, we will return the string.

Let’s see the code for better understanding.

class Solution:
def removeOccurrences(self, s: str, part: str) -> str:
while part in s:
s = s.replace(part, '', 1)
return s

Conclusion

There are many solutions to this problem. I hope this one will help you.

This answer will be accepted. But before submitting an answer, try to understand the whole thing. And try to go through the code with a simple test case for better understanding. It helps a lot.