Merge pull request #1891 from DraymondHIT/master

添加 0028找出字符串中第一个匹配项的下标 前缀表(不减一) Python 版本
This commit is contained in:
程序员Carl
2023-02-14 10:43:30 +08:00
committed by GitHub

View File

@ -769,6 +769,36 @@ class Solution:
return next return next
``` ```
```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
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
```
Go Go
```go ```go
@ -1352,3 +1382,4 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank"> <a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/> <img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a> </a>