# 28. Implement strStr() [easy] (Python)

## 题目链接

https://leetcode.com/problems/implement-strstr/

## 题目原文

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

## 思路方法

### 思路一

class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
return haystack.find(needle)

### 思路二

class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
for i in xrange(len(haystack) - len(needle) + 1):
if haystack[i] == needle[0]:
j = 1
while j < len(needle) and haystack[i+j] == needle[j]:
j += 1
if j == len(needle):
return i
return -1

### 思路三

class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
for i in xrange(len(haystack) - len(needle) + 1):
if haystack[i:i+len(needle)] == needle:
return i
return -1

### 思路四

class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
#generate next array, need O(n) time
i, j, m, n = -1, 0, len(haystack), len(needle)
next = [-1] * n
while j < n - 1:
#needle[k] stands for prefix, neelde[j] stands for postfix
if i == -1 or needle[i] == needle[j]:
i, j = i + 1, j + 1
next[j] = i
else:
i = next[i]
#check through the haystack using next, need O(m) time
i = j = 0
while i < m and j < n:
if j == -1 or haystack[i] == needle[j]:
i, j = i + 1, j + 1
else:
j = next[j]
if j == n:
return i - j
return -1

PS: 新手刷LeetCode，新手写博客，写错了或者写的不清楚还请帮忙指出，谢谢！