添加了python版本代码

为数据结构和算法文件夹下的代码增加了python语言版本
This commit is contained in:
goodyong
2021-07-05 22:25:41 +08:00
parent a503e97f11
commit 4e661354d4
16 changed files with 1088 additions and 83 deletions

View File

@@ -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
```