能否使用python语言
时间: 2023-10-09 07:06:53 浏览: 81
OpenCV4.6.5所有内部函数实际使用以及说明(python语言)
当然可以,下面是同样的 KMP 算法的 Python 实现示例,供参考:
```python
def get_next(pattern: str) -> List[int]:
n = len(pattern)
next = [-1] * n
i, j = 0, -1
while i < n - 1:
if j == -1 or pattern[i] == pattern[j]:
i += 1
j += 1
next[i] = j
else:
j = next[j]
return next
def kmp(text: str, pattern: str) -> int:
m, n = len(text), len(pattern)
if n == 0:
return 0
next = get_next(pattern)
i, j = 0, 0
while i < m and j < n:
if j == -1 or text[i] == pattern[j]:
i += 1
j += 1
else:
j = next[j]
if j == n:
return i - n
else:
return -1
# 测试用例
s1 = "hello world"
n1 = "world"
print(kmp(s1, n1)) # expect 6
s2 = "hello world"
n2 = "worl"
print(kmp(s2, n2)) # expect -1
s3 = "hello world"
n3 = ""
print(kmp(s3, n3)) # expect 0
s4 = "aaa"
n4 = "a"
print(kmp(s4, n4)) # expect 0
s5 = "aaa"
n5 = "b"
print(kmp(s5, n5)) # expect -1
```
以上 Python 代码与 C++ 代码类似,都是先实现了 `get_next` 函数来计算模式串的 `next` 数组,然后再使用 `kmp` 函数来匹配字符串。
阅读全文