Find index of the first occurrence in a string
28. Find the Index of the First Occurrence in a String
Easy
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 <= 104haystackandneedleconsist of only lowercase English characters.
- 1
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)
- 2
OTHER code:
- -
Rabin Karp algo(used in this solution)
- Rabin Karp, built-in hash, constant time (tested)
def strStr(self, haystack, needle):
n, h = len(needle), len(haystack)
hash_n = hash(needle)
for i in range(h-n+1):
if hash(haystack[i:i+n]) == hash_n:
return i
return -1- Rabin Karp, numeral base for both uppercase and lowercase letters, constant time
def strStr(self, haystack, needle):
def f(c):
return ord(c)-ord('A')
n, h, d, m = len(needle), len(haystack), ord('z')-ord('A')+1, sys.maxint
if n > h: return -1
nd, hash_n, hash_h = d**(n-1), 0, 0
for i in range(n):
hash_n = (d*hash_n+f(needle[i]))%m
hash_h = (d*hash_h+f(haystack[i]))%m
if hash_n == hash_h: return 0
for i in range(1, h-n+1):
hash_h = (d*(hash_h-f(haystack[i-1])*nd)+f(haystack[i+n-1]))%m # e.g. 10*(1234-1*10**3)+5=2345
if hash_n == hash_h: return i
return -1
- KMP (KMP algo used in this sol)
def strStr(self, haystack, needle):
n, h = len(needle), len(haystack)
i, j, nxt = 1, 0, [-1]+[0]*n
while i < n: # calculate next array
if j == -1 or needle[i] == needle[j]:
i += 1
j += 1
nxt[i] = j
else:
j = nxt[j]
i = j = 0
while i < h and j < n:
if j == -1 or haystack[i] == needle[j]:
i += 1
j += 1
else:
j = nxt[j]
return i-j if j == n else -1
Comments
Post a Comment