28. 实现 strStr() Implement strStr()

题目:28.实现 strStr() Implement strStr()

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。

示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

参考答案

这道题解题也不是很难,就是卡在寻址是0开始,计算长度是1开始,所以这里特别要注意

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        # 首先 对输入的内容进行判断
        if len(needle) == 0:
            return 0 
        if len(haystack) == 0:
            return -1
        
        # 然后是长度判断
        if len(needle) > len(haystack):
            return -1
        
        
        # tag 位置标记 
        # index_hay 指针标记
        # index_nee 指针标记
        
        # 循环遍历 haystack 中的数据,如果发现与 needle 首位相同的数据,进入匹配环节
        for index_hay in range(len(haystack)):
            if haystack[index_hay] == needle[0]:
                # tag 标记当前位置(以0开始)
                tag = index_hay
                # 匹配环节,如果不符合条件,跳出继续进入索引的搜索
                for index_nee in range(len(needle)+1):
                    if tag + index_nee + 1 > len(haystack): # 如果超出索引的长度,跳出循环
                        return -1
                    elif needle[index_nee] != haystack[tag+index_nee]: # 如果按位匹对,不相等跳出循环
                        break
                    elif index_nee + 1 == len(needle):
                        return tag
        return -1

欢迎提问,每天晚上都会定期回复~~

猜你喜欢

转载自blog.csdn.net/q370835062/article/details/84680282