NO28.实现strStr()

# 有点问题,解决了数组越界后但还是发生错误,待解决
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if not needle:
            return 0
        if len(needle)>len(haystack):
            return -1
        if haystack==needle:
            return 0
        for i in range(len(haystack)):
            flag=1
            k=i
            for j in range(len(needle)):
                if haystack[k]!=needle[j] :
                    flag=0 
                elif haystack[k]!=needle[j] and k<len(haystack):
                    k+=1
                if flag==0:
                    break
            if flag==1:
                return i
        return -1
#调用python的内部函数.find,返回haystack第一个查到的下标
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if needle == "":
            return 0
        else:
            return haystack.find(needle)
#python'进行切片处理,i:i+n进行比较相等则返回i
class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        if not needle or len(needle) == 0 :#特例处理
            return 0
        n = len(needle)
        i = 0
        while i <= (len(haystack)-n):   ##等于两个字符串长度相减时,移位完毕
            if haystack[i:i+n] == needle:  ##依次移位,判断i+n(n为第二个字符串长度)是否相等
                return i
            else:
                i += 1
        if i > (len(haystack)-n):
            return -1

 

 
posted @ 2022-07-14 16:32  是冰美式诶  阅读(23)  评论(0)    收藏  举报