实现strStr()---LeetCode----(13)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_36697353/article/details/87903910

实现 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() 定义相符。

首先这道题有两种解法, 第一种就是最简答的,有内置函数,别人已经写好的。但是这种没有锻炼的任何意义,但是可以熟悉一哈内置函数,哈哈

1.内置函数方法:

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """            
        return haystack.find(needle)

 第二种方法,自己实现。KMP算法

参考如下:  https://www.cnblogs.com/en-heng/p/5091365.html

首先,暴力解法:

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if needle not in haystack:
            return -1
        if len(needle) ==1 :
            return 0
        if len(needle) > len(haystack):
            return -1
        i,j = 0,0
        while(i<len(haystack) and j <len(needle)):
            if(haystack[i] == needle[j]):
                i+=1
                j+=1
            else:
                i = i-j+1
                j=0
        
        if j ==len(needle):
            return i-j
        else:
            return -1

暴力解法,效率不高,KMP算法:

猜你喜欢

转载自blog.csdn.net/baidu_36697353/article/details/87903910