Skip to content

Commit ac3f9b8

Browse files
author
“DraymondHIT”
committed
添加 0028找出字符串中第一个匹配项的下标 前缀表(不减一) Python 版本
1 parent 6884c44 commit ac3f9b8

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

problems/0028.实现strStr.md

+31
Original file line numberDiff line numberDiff line change
@@ -769,6 +769,36 @@ class Solution:
769769
return next
770770
```
771771

772+
```python
773+
// 前缀表(不减一)Python实现
774+
class Solution:
775+
def strStr(self, haystack: str, needle: str) -> int:
776+
if len(needle) == 0:
777+
return 0
778+
next = self.getNext(needle)
779+
j = 0
780+
for i in range(len(haystack)):
781+
while j >= 1 and haystack[i] != needle[j]:
782+
j = next[j-1]
783+
if haystack[i] == needle[j]:
784+
j += 1
785+
if j == len(needle):
786+
return i - len(needle) + 1
787+
return -1
788+
789+
def getNext(self, needle):
790+
next = [0] * len(needle)
791+
j = 0
792+
next[0] = j
793+
for i in range(1, len(needle)):
794+
while j >= 1 and needle[i] != needle[j]:
795+
j = next[j-1]
796+
if needle[i] == needle[j]:
797+
j += 1
798+
next[i] = j
799+
return next
800+
```
801+
772802
Go:
773803

774804
```go
@@ -1352,3 +1382,4 @@ impl Solution {
13521382
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
13531383
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
13541384
</a>
1385+

0 commit comments

Comments
 (0)