Update 0028.实现strStr.md

This commit is contained in:
jianghongcheng
2023-05-06 19:39:34 -05:00
committed by GitHub
parent 7cfd389402
commit 3cf5502868

View File

@ -692,23 +692,38 @@ class Solution {
```
Python3
(版本一)前缀表(不减一)
```python
//暴力解法
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
m, n = len(haystack), len(needle)
for i in range(m):
if haystack[i:i+n] == needle:
return i
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
next = self.getNext(needle)
j = 0
for i in range(len(haystack)):
while j >= 1 and haystack[i] != needle[j]:
j = next[j-1]
if haystack[i] == needle[j]:
j += 1
if j == len(needle):
return i - len(needle) + 1
return -1
def getNext(self, needle):
next = [0] * len(needle)
j = 0
next[0] = j
for i in range(1, len(needle)):
while j >= 1 and needle[i] != needle[j]:
j = next[j-1]
if needle[i] == needle[j]:
j += 1
next[i] = j
return next
```
(版本二)前缀表(减一)
```python
// 方法一
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
a = len(needle)
@ -739,8 +754,11 @@ class Solution:
return next
```
(版本三)前缀表(减一)
```python
// 方法二
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
a = len(needle)
@ -774,35 +792,36 @@ class Solution:
return next
```
(版本四)暴力法
```python
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
m, n = len(haystack), len(needle)
for i in range(m):
if haystack[i:i+n] == needle:
return i
return -1
```
(版本五)使用 index
```python
// 前缀表不减一Python实现
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
next = self.getNext(needle)
j = 0
for i in range(len(haystack)):
while j >= 1 and haystack[i] != needle[j]:
j = next[j-1]
if haystack[i] == needle[j]:
j += 1
if j == len(needle):
return i - len(needle) + 1
try:
return haystack.index(needle)
except ValueError:
return -1
def getNext(self, needle):
next = [0] * len(needle)
j = 0
next[0] = j
for i in range(1, len(needle)):
while j >= 1 and needle[i] != needle[j]:
j = next[j-1]
if needle[i] == needle[j]:
j += 1
next[i] = j
return next
```
(版本六)使用 find
```python
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)
Go