给定一个s字符串和一个n字符串,在s字符串中找出n字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1
时间: 2024-01-21 09:19:05 浏览: 58
以下是 Python 代码实现:
```python
def find_first_occurrence(s, n):
if not s or not n: # 处理空字符串的情况
return -1
n_len = len(n)
for i in range(len(s) - n_len + 1):
if s[i:i+n_len] == n:
return i
return -1 # 没有找到匹配的子串,返回 -1
```
该函数的时间复杂度为 $O(mn)$,其中 $m$ 和 $n$ 分别是两个字符串的长度。在最坏情况下,需要比较 $m-n+1$ 个子串,每个子串需要比较 $n$ 个字符,因此总的比较次数为 $(m-n+1)\times n$。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![java](https://img-home.csdnimg.cn/images/20250102104920.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)