Skip to content

Commit 220d5b1

Browse files
authored
Create remove-all-occurrences-of-a-substring.py
1 parent 4e252ae commit 220d5b1

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Time: O(n + m)
2+
# Space: O(n + m)
3+
4+
# kmp solution
5+
class Solution(object):
6+
def removeOccurrences(self, s, part):
7+
"""
8+
:type s: str
9+
:type part: str
10+
:rtype: str
11+
"""
12+
def getPrefix(pattern):
13+
prefix = [-1]*len(pattern)
14+
j = -1
15+
for i in xrange(1, len(pattern)):
16+
while j != -1 and pattern[j+1] != pattern[i]:
17+
j = prefix[j]
18+
if pattern[j+1] == pattern[i]:
19+
j += 1
20+
prefix[i] = j
21+
return prefix
22+
23+
prefix = getPrefix(part)
24+
result, lookup = [], []
25+
i = -1
26+
for c in s:
27+
while i != -1 and part[i+1] != c:
28+
i = prefix[i]
29+
if part[i+1] == c:
30+
i += 1
31+
result.append(c)
32+
lookup.append(i)
33+
if i == len(part)-1:
34+
result[len(result)-len(part):] = []
35+
lookup[len(lookup)-len(part):] = []
36+
i = lookup[-1] if lookup else -1
37+
return "".join(result)

0 commit comments

Comments
 (0)