28.leetcode 实现 strStr()(简单)

leetcode python 刷题记录,从易到难

一、题目

在这里插入图片描述

二、解答

1.思路

  • 非空判断
  • 遍历目标字符串,挨个比对,如果当前字符等于要找的目标字符
  • 那就再判断当前索引到要找的字符串长度加当前索引的位置的字符串是否要找的目标字符串
  • 如果找到了,那就反回当前索引
  • 找不到则返回-1

2.实现

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if not needle:
            return 0
        if not haystack:
            return -1
        for i in range(0,len(haystack)):
            if haystack[i] is needle[0] and haystack[i:len(needle)+i] == needle:
                index = i
                return i
        else:
            return -1

3.提交

在这里插入图片描述

4.Github地址

https://github.com/m769963249/leetcode_python_solution/blob/master/easy/28.py

猜你喜欢

转载自blog.csdn.net/qq_39945938/article/details/108298012