【LeetCode 简单题】9-实现 strStr() 函数

声明:

今天是第9道题,实现 strStr() 函数。给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。以下所有代码经过楼主验证都能在LeetCode上执行成功,代码也是借鉴别人的,在文末会附上参考的博客链接,如果侵犯了博主的相关权益,请联系我删除

(手动比心ღ( ´・ᴗ・` ))

正文

题目:实现 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。用字符串固有的index索引属性,从第1个元素开始截取长度等于needle的substring,直到第len(haystack)-len(needle)这个位置。还例举了1种更简便的方法,利用的是Python API多的优势。

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        # V 1.0,能提交
        if len(needle) == 0:
            return 0
        # 注意这里range里的len相减后为什么要+1,楼主举例实验了一下,
        # 因为range(5)表示的是0-4,不包括5,最后1个匹配的位置应该是len(hay)-len(nee),所以要+1
        for i in range(len(haystack)-len(needle)+1):
            if haystack[i:i+len(needle)] == needle:
                return i
        return -1
        
        # V 2.0,能提交,但不符合题目要求(要自己实现),直接调用Python的find函数即可
        if not needle:
            return 0
        return haystack.find(needle)

解法2。楼主看半天KMP算法没整明白,这里就先贴出从别人那粘过来的代码。仅供参考一下,有空我再仔细琢磨一下解释。

class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """      
        if not needle:
            return 0
        #generate next array, need O(n) time
        i, j, m, n = -1, 0, len(haystack), len(needle)
        next = [-1] * n
        while j < n - 1:  
            #needle[k] stands for prefix, neelde[j] stands for postfix
            if i == -1 or needle[i] == needle[j]:   
                i, j = i + 1, j + 1
                next[j] = i
            else:
                i = next[i]
        #check through the haystack using next, need O(m) time
        i = j = 0
        while i < m and j < n:
            if j == -1 or haystack[i] == needle[j]:
                i, j = i + 1, j + 1
            else:
                j = next[j]
        if j == n:
            return i - j
        return -1

结尾

解法1:https://blog.csdn.net/coder_orz/article/details/51708389

解法2(代码是从解法1中粘过来的,此链接是KMP的解释):

https://blog.csdn.net/v_july_v/article/details/7041827

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/82555544
今日推荐