# leetcode 1910. Remove All Occurrences of a Substring（python）

2022-01-31 17:19:53

「 This is my participation 11 The fourth of the yuegengwen challenge 17 God , Check out the activity details ：2021 One last more challenge

### describe

Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed:

• Find the leftmost occurrence of the substring part and remove it from s.

Return s after removing all occurrences of part.

A substring is a contiguous sequence of characters in a string.

Example 1:

``````Input: s = "daabcbaabcbc", part = "abc"
Output: "dab"
Explanation: The following operations are done:
- s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc".
- s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc".
- s = "dababc", remove "abc" starting at index 3, so s = "dab".
Now s has no occurrences of "abc".
Copy code ``````

Example 2:

``````Input: s = "axxxxyyyyb", part = "xy"
Output: "ab"
Explanation: The following operations are done:
- s = "axxxxyyyyb", remove "xy" starting at index 4 so s = "axxxyyyb".
- s = "axxxyyyb", remove "xy" starting at index 3 so s = "axxyyb".
- s = "axxyyb", remove "xy" starting at index 2 so s = "axyb".
- s = "axyb", remove "xy" starting at index 1 so s = "ab".
Now s has no occurrences of "xy".
Copy code ``````

Note:

``````1 <= s.length <= 1000
1 <= part.length <= 1000
s​​​​​​ and part consists of lowercase English letters.
Copy code ``````

### analysis

According to the meaning , Give a string s And a string part , Yes s Do the following , Until all substrings appear are deleted part：

• Find the leftmost substring part And take it from s Delete in

Delete all occurrences part After the return s. At the same time, the title also kindly gives the meaning of the substring ： A substring is a sequence of consecutive characters in a string .

In fact, after reading the title, we will know , The problem is very simple , Is to investigate the basic operation of searching and indexing characters in a string , Use one while loop , Use python Built in functions for find If in s You can find the leftmost part The starting index that appears i let , let s[:i] + s[i+len(part):] Replace old s , until while Loop cannot be from s Find part until , Finally back to s that will do .

``````class Solution(object):
def removeOccurrences(self, s, part):
"""
:type s: str
:type part: str
:rtype: str
"""
while s.find(part)!=-1:
i = s.find(part)
s = s[:i] + s[i+len(part):]
return s

Copy code ``````

### Running results

``````Runtime: 16 ms, faster than 94.40% of Python online submissions for Remove All Occurrences of a Substring.
Memory Usage: 13.6 MB, less than 61.60% of Python online submissions for Remove All Occurrences of a Substring.
Copy code ``````