mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2025-10-19 05:52:25 +00:00
添加了python版本代码
为数据结构和算法文件夹下的代码增加了python语言版本
This commit is contained in:
@@ -113,7 +113,7 @@ class Solution {
|
||||
k = next[k];
|
||||
}
|
||||
// 相同情况,就是 k的下一位,和 i 相同时,此时我们已经知道 [0,i-1]的最长前后缀
|
||||
//然后 k - 1 又和 i 相同,最长前后缀加1,即可
|
||||
//然后 k + 1 又和 i 相同,最长前后缀加1,即可
|
||||
if (needle[k+1] == needle[i]) {
|
||||
++k;
|
||||
}
|
||||
@@ -125,5 +125,63 @@ class Solution {
|
||||
}
|
||||
```
|
||||
|
||||
Python Code:
|
||||
|
||||
```python
|
||||
from typing import List
|
||||
class Solution:
|
||||
def strStr(self, haystack: str, needle: str)->int:
|
||||
# 两种特殊情况
|
||||
if len(needle) == 0:
|
||||
return 0
|
||||
if len(haystack) == 0:
|
||||
return -1
|
||||
# 长度
|
||||
halen = len(haystack)
|
||||
nelen = len(needle)
|
||||
# 返回下标
|
||||
return self.kmp(haystack, halen, needle, nelen)
|
||||
|
||||
def kmp(self, hasyarr: str, halen: int, nearr: str, nelen: int)->int:
|
||||
# 获取next 数组
|
||||
next = self.next(nearr, nelen)
|
||||
j = 0
|
||||
for i in range(0, halen):
|
||||
# 发现不匹配的字符,然后根据 next 数组移动指针,移动到最大公共前后缀的,
|
||||
# 前缀的后一位,和咱们移动模式串的含义相同
|
||||
while j > 0 and hasyarr[i] != nearr[j]:
|
||||
j = next[j - 1] + 1
|
||||
# 超出长度时,可以直接返回不存在
|
||||
if nelen - j + i > halen:
|
||||
return -1
|
||||
# 如果相同就将指针同时后移一下,比较下个字符
|
||||
if hasyarr[i] == nearr[j]:
|
||||
j += 1
|
||||
# 遍历完整个模式串,返回模式串的起点下标
|
||||
if j == nelen:
|
||||
return i - nelen + 1
|
||||
return -1
|
||||
|
||||
# 这一块比较难懂,不想看的同学可以忽略,了解大致含义即可,或者自己调试一下,看看运行情况
|
||||
# 我会每一步都写上注释
|
||||
def next(self, needle: str, len:int)->List[int]:
|
||||
# 定义 next 数组
|
||||
next = [0] * len
|
||||
# 初始化
|
||||
next[0] = -1
|
||||
k = -1
|
||||
for i in range(1, len):
|
||||
# 我们此时知道了 [0,i-1]的最长前后缀,但是k+1的指向的值和i不相同时,我们则需要回溯
|
||||
# 因为 next[k]就时用来记录子串的最长公共前后缀的尾坐标(即长度)
|
||||
# 就要找 k+1前一个元素在next数组里的值,即next[k+1]
|
||||
while k != -1 and needle[k + 1] != needle[i]:
|
||||
k = next[k]
|
||||
# 相同情况,就是 k的下一位,和 i 相同时,此时我们已经知道 [0,i-1]的最长前后缀
|
||||
# 然后 k + 1 又和 i 相同,最长前后缀加1,即可
|
||||
if needle[k + 1] == needle[i]:
|
||||
k += 1
|
||||
next[i] = k
|
||||
return next
|
||||
```
|
||||
|
||||
|
||||
|
Reference in New Issue
Block a user