-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImplement_strStr().py
More file actions
75 lines (56 loc) · 1.58 KB
/
Copy pathImplement_strStr().py
File metadata and controls
75 lines (56 loc) · 1.58 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
"""
################################# KMP Solution #################################
class Solution:
# @param haystack, a string
# @param needle, a string
# @return a string or None
def strStr(self, haystack, needle):
# base cases
if len(needle) == 0: return 0
if len(haystack) == 0: return -1
shifts = self.create_shifts_arr(needle)
i = 0; j = 0
while i < len(haystack):
while j >= 0 and haystack[i] != needle[j]:
j = shifts[j]
i += 1; j += 1
if j >= len(needle):
return haystack[(i-j):]
return None
# shifts array: proper prefix in the (sub)pattern that
# matches a proper suffix in the same (sub)pattern.
def create_shifts_arr(self, pattern):
M = len(pattern)
shifts = [0] * (M+1)
shifts[0] = -1
i = 0; j = -1
while i < M:
while j >= 0 and pattern[i] != pattern[j]:
j = shifts[j]
i += 1; j += 1
shifts[i] = j
return shifts
################################# Brute force Solution #################################
class Solution:
# @param haystack, a string
# @param needle, a string
# @return a string or None
def strStr(self, haystack, needle):
m = len(haystack)
n = len(needle)
# base cases
if n == 0: return 0
if m == 0: return -1
for i in range(m - n + 1):
for j in range(n):
# match failed
if haystack[i+j] != needle[j]: break
# sucees
if j == n - 1: return i
# failure
return -1
s = Solution()
print s.strStr("mississippi", "issip")