-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathImplementStrStr.py
More file actions
30 lines (29 loc) · 882 Bytes
/
ImplementStrStr.py
File metadata and controls
30 lines (29 loc) · 882 Bytes
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
class Solution:
# @param haystack, a string
# @param needle, a string
# @return a string or None
def strStr(self, haystack, needle):
m = len(needle)
n = len(haystack)
if m==0:
return haystack
def compute_fail(needle,next):
next[0]=-1
j = -1
for i in xrange(1,m):
while j!=-1 and needle[i]!=needle[j+1]:
j=next[j]
if needle[i]==needle[j+1]:
j+=1
next[i]=j
next = [-1]*m
compute_fail(needle,next)
j = -1
for i in xrange(n):
while j!=-1 and haystack[i]!=needle[j+1]:
j = next[j]
if haystack[i]==needle[j+1]:
j+=1
if j==m-1:
return haystack[i-m+1:]
return None