LeetCode28:Implement strStr()

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().


LeetCode:链接

参考链接:点这里

这题就是最长公共字符串匹配。

第一种方法:暴力匹配法

即从haystack开始第一个字符与needle第一个字符匹配,如果匹配,则i++,j++,继续往下走,否则中间一旦发生不匹配,则haystack则从第二个字符开始于needle第一个字符重新开始匹配。重复这个过程,如果中间j走到needle结尾,则匹配成功,如果i走到了haystack结尾处,而j还没有,则匹配失败。

必须得有needle长度那么大才可以判断,不能for i in range(n),会超时。

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        if not needle:
            return 0
        n = len(haystack)
        m = len(needle)
        '''必须得有needle长度那么大才可以判断 不能for i in range(n) 会超时'''
        for i in range(n-m+1):
            j = 0
            '''在needle范围内判断'''
            while j < m:
                '''只要有不相等 直接退出循环'''
                if haystack[i+j] != needle[j]:
                    break
                j += 1
            '''如果此时的j和needle的长度相等 说明匹配到了'''
            if j == m:
                return i 
        return -1

第二种方法:KMP。

东方闪电

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/84062267