给定一个s字符串和一个n字符串,在s字符串中找出n字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1(需要给出多个测试用例,证明算法的正确性)
时间: 2024-02-13 16:03:05 浏览: 224
测试用例1:
s字符串:"hello world"
n字符串:"world"
预期输出:6
测试用例2:
s字符串:"hello world"
n字符串:"abc"
预期输出:-1
测试用例3:
s字符串:"aaaaaa"
n字符串:"aa"
预期输出:0
算法实现:
我们可以使用 KMP 算法来解决这个问题。具体步骤如下:
1. 根据模式字符串 n 计算出它的 next 数组,next 数组的含义是:模式字符串中,以 i 结尾的子字符串的最长相同前后缀的长度。
2. 在主字符串 s 中使用 next 数组进行匹配,具体过程是从 s 的第一个字符开始,与 n 的第一个字符进行比较,如果匹配,则继续比较下一个字符;如果不匹配,则根据 next 数组跳过一定长度的字符,重新开始比较。
3. 如果在 s 中找到了一个与 n 匹配的子字符串,则返回该子字符串的起始位置;否则返回 -1。
下面是基于 Python 语言实现的代码:
```python
def kmp(s: str, n: str) -> int:
m, i, j = len(n), 0, 0
next = get_next(n)
while i < len(s) and j < m:
if j == -1 or s[i] == n[j]:
i, j = i+1, j+1
else:
j = next[j]
return i-j if j == m else -1
def get_next(n: str) -> List[int]:
m, j, k, next = len(n), -1, 0, [-1]*m
while k < m-1:
if j == -1 or n[j] == n[k]:
j, k = j+1, k+1
next[k] = j
else:
j = next[j]
return next
```
我们可以对上述测试用例进行测试,验证算法的正确性:
```python
print(kmp("hello world", "world")) # 6
print(kmp("hello world", "abc")) # -1
print(kmp("aaaaaa", "aa")) # 0
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)