28. 实现 strStr()
题目:
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
链接 https://leetcode.cn/problems/implement-strstr/
个人思路
-
python find 方法
首先判断needle字符串长度是否为0,是则直接返回0,否则使用find方法即可 -
但一味使用python自带方法那刷题则毫无意义且不利于笔试面试,这里尝试自己暴力解法
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
else:
for i in range(len(haystack)):
if len(haystack)-i < len(needle):
return -1
if haystack[i] == needle[0]:
# 本来不想从0开始,但就要增加一个字符串长度为1的判断
for j in range(0,len(needle)):
# 对比接下来needle的每个字符是否和haystack接下来的字符一致
if needle[j] != haystack[i+j]:
break
# 如果needle能在haystack中找到,则返回下标
elif j == len(needle)-1:
return i
return -1
复杂度分析
时间复杂度:略
空间复杂度:略
其他思路
- 暴力解法
让字符串needle 与字符串 haystack 的所有长度为 mm 的子串均匹配一次
时间复杂度: O(n×m),其中 nn 是字符串 ,haystack 的长度,mm 是字符串needle 的长度。最坏情况下我们需要将字符串needle 与字符串haystack 的所有长度为 mm 的子串均匹配一次。
空间复杂度:O(1)。我们只需要常数的空间保存若干变量。
- KMP算法
具体可以参照下面链接:
知乎:https://www.zhihu.com/question/21923021/answer/281346746
LeetCode:https://leetcode.cn/problems/implement-strstr/solution/shua-chuan-lc-shuang-bai-po-su-jie-fa-km-tb86/
LeetCode:https://leetcode.cn/problems/implement-strstr/solution/dai-ma-sui-xiang-lu-kmpsuan-fa-xiang-jie-mfbs/
// 方法一
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
a=len(needle)
b=len(haystack)
if a==0:
return 0
next=self.getnext(a,needle)
p=-1
for j in range(b):
while p>=0 and needle[p+1]!=haystack[j]:
p=next[p]
if needle[p+1]==haystack[j]:
p+=1
if p==a-1:
return j-a+1
return -1
def getnext(self,a,needle):
next=['' for i in range(a)]
k=-1
next[0]=k
for i in range(1,len(needle)):
while (k>-1 and needle[k+1]!=needle[i]):
k=next[k]
if needle[k+1]==needle[i]:
k+=1
next[i]=k
return next
- Sunday 算法
Sunday 匹配机制
目标字符串String
模式串 Pattern
当前查询索引 idx (初始为 00)
待匹配字符串 str_cut : String [ idx : idx + len(Pattern) ]
每次匹配都会从 目标字符串中 提取 待匹配字符串与 模式串 进行匹配:
若匹配,则返回当前 idx
不匹配,则查看 待匹配字符串 的后一位字符 c:
若c存在于Pattern中,则 idx = idx + 偏移表[c]
否则,idx = idx + len(pattern)
Repeat Loop 直到 idx + len(pattern) > len(String)
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
# Func: 计算偏移表
def calShiftMat(st):
dic = {}
for i in range(len(st)-1,-1,-1):
if not dic.get(st[i]):
dic[st[i]] = len(st)-i
dic["ot"] = len(st)+1
return dic
# 其他情况判断
if len(needle) > len(haystack):return -1
if needle=="": return 0
# 偏移表预处理
dic = calShiftMat(needle)
idx = 0
while idx+len(needle) <= len(haystack):
# 待匹配字符串
str_cut = haystack[idx:idx+len(needle)]
# 判断是否匹配
if str_cut==needle:
return idx
else:
# 边界处理
if idx+len(needle) >= len(haystack):
return -1
# 不匹配情况下,根据下一个字符的偏移,移动idx
cur_c = haystack[idx+len(needle)]
if dic.get(cur_c):
idx += dic[cur_c]
else:
idx += dic["ot"]
return -1 if idx+len(needle) >= len(haystack) else idx
作者:Tes
链接:https://leetcode.cn/problems/implement-strstr/solution/python3-sundayjie-fa-9996-by-tes/
来源:力扣(LeetCode)