forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove-all-occurrences-of-a-substring.py
More file actions
37 lines (35 loc) · 1.06 KB
/
remove-all-occurrences-of-a-substring.py
File metadata and controls
37 lines (35 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Time: O(n + m)
# Space: O(n + m)
# kmp solution
class Solution(object):
def removeOccurrences(self, s, part):
"""
:type s: str
:type part: str
:rtype: str
"""
def getPrefix(pattern):
prefix = [-1]*len(pattern)
j = -1
for i in xrange(1, len(pattern)):
while j != -1 and pattern[j+1] != pattern[i]:
j = prefix[j]
if pattern[j+1] == pattern[i]:
j += 1
prefix[i] = j
return prefix
prefix = getPrefix(part)
result, lookup = [], []
i = -1
for c in s:
while i != -1 and part[i+1] != c:
i = prefix[i]
if part[i+1] == c:
i += 1
result.append(c)
lookup.append(i)
if i == len(part)-1:
result[len(result)-len(part):] = []
lookup[len(lookup)-len(part):] = []
i = lookup[-1] if lookup else -1
return "".join(result)