@[TOC](leetcode_28. 实现 strStr())
题目
思路分析
题目要求:普通模式串匹配
2层遍历
- i 可以遍历到 hlen-nlen+1
- j 可以用来 对 子串,模式串 统一向后遍历
代码展示
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
#特殊情况处理
if haystack == '' and needle =='':
return 0
if needle == '':
return 0
hlen = len(haystack)
nlen = len(needle)
# for i in range(haystack):
# i 可以遍历到 hlen-nlen+1
for i in range(hlen-nlen+1):
if needle[0]==haystack[i]:
j = 0
# j 可以用来 对 子串,模式串 统一向后遍历
while j<nlen and needle[j]==haystack[j+i]:
j+=1
#子串一直遍历到尾,说明找到匹配子串
if j == nlen:
return i
return -1