leetcode 28:实现 strStr() 函数。

题目描述:

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

示例 1:

输入: haystack = "hello", needle = "ll"
输出: 2

解题思路:

方法一:子串逐一匹配

将长度为 L 的滑动窗口沿着 haystack 字符串逐步移动,并将窗口内的子串与 needle 字符串相比较,时间复杂度为O((N−L)L)

class Solution:
    def strStr(self, haystack: str, needle: str) -> int:
        L, n = len(needle), len(haystack)

        for start in range(n - L + 1):
            if haystack[start: start + L] == needle:
                return start
        return -1

方法二:双指针查找

只有子串的第一个字符跟 needle 字符串第一个字符相同的时候才需要比较,一个字符一个字符比较,一旦不匹配了就立刻终止。注意不匹配的时候指针需要回溯。

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        l1,l2=len(haystack),len(needle)
        if l2==0:
            return 0
        i=0
        while i<l1-l2+1:
            p=i
            j,cur_len=0,0
            while i<l1-l2+1 and haystack[i]!=needle[0]:
                i+=1
            while i<l1 and j<l2 and haystack[i]==needle[j]:
                i+=1
                j+=1
                cur_len+=1
                #print(i,j,cur_len)
            if cur_len==l2:
                return i-l2
            #i=i-j+1   #回溯到初始位置的下一个
            i=p+1
        return -1

猜你喜欢

转载自blog.csdn.net/qq_36854740/article/details/107522574