28. 实现 strStr()
题目要求:
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
题解思路:
- 遍历haystack 字符串中的每个长度为needle 字符串长度的子字符串;
- 判断子字符串是否和needle 字符串相等;返回对应的结果。
解题代码:
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
#计算 haystack 字符串和needle 字符串的长度
n = len(haystack)
m = len(needle)
#遍历每个长度为needle 字符串长度的子字符串
for i in range(n-m+1):
#判断子字符串是否和needle 字符串相等
if haystack[i:i+m] == needle:
return i
return -1
效果也是不错的!
我的leetcode.
(“你需要坚持的三件事:积极向上,关心身边人,锻炼身体。
”FIGHTING. . . .)