-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
110 lines (95 loc) · 2.89 KB
/
main.py
File metadata and controls
110 lines (95 loc) · 2.89 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# Source: https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string
# Title: Find the Index of the First Occurrence in a String
# Difficulty: Easy
# Author: Mu Yang <http://muyang.pro>
################################################################################################################################
# Given two strings `needle` and `haystack`, return the index of the first occurrence of `needle` in `haystack`, or `-1` if `needle` is not part of `haystack`.
#
# **Example 1:**
#
# ```
# Input: haystack = "sadbutsad", needle = "sad"
# Output: 0
# Explanation: "sad" occurs at index 0 and 6.
# The first occurrence is at index 0, so we return 0.
# ```
#
# **Example 2:**
#
# ```
# Input: haystack = "leetcode", needle = "leeto"
# Output: -1
# Explanation: "leeto" did not occur in "leetcode", so we return -1.
# ```
#
# **Constraints:**
#
# - `1 <= haystack.length, needle.length <= 10^4`
# - `haystack` and `needle` consist of only lowercase English characters.
#
################################################################################################################################
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)
# Naive
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n = len(haystack)
m = len(needle)
if n < m:
return -1
for i in range(n - m + 1):
if haystack[i : i + m] == needle:
return i
return -1
# Rabin-Karp Algorithm
#
# Use char sum as hash
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n = len(haystack)
m = len(needle)
if n < m:
return -1
needle_hash = sum((ord(ch) for ch in needle))
curr_hash = sum((ord(ch) for ch in haystack[: m - 1]))
for i in range(n - m + 1):
curr_hash += ord(haystack[i + m - 1])
if curr_hash == needle_hash:
if haystack[i : i + m] == needle:
return i
curr_hash -= ord(haystack[i])
return -1
# KMP Algorithm
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
n = len(haystack)
m = len(needle)
if n < m:
return -1
# LPS
lps = [0] * m
i, j = 1, 0
while i < m:
if needle[i] == needle[j]:
j += 1
lps[i] = j
i += 1
elif j > 0:
j = lps[j - 1]
else:
lps[i] = 0
i += 1
# Search
i, j = 0, 0
while i < n:
if haystack[i] == needle[j]:
i += 1
j += 1
if j == m:
return i - m
elif j > 0:
j = lps[j - 1]
else:
i += 1
return -1