Q28 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
解题思路:

此题即实现Python中内置函数 find() 的功能。简单方法就是逐个字符比较,当匹配失效后,将子串重新移到开始位置,主串回退前面已经匹配的n个字符,然后继续比较。时间复杂度 O(m*n)

注意点:

此题可采用 KMP 算法求解,时间复杂度可以降为 O(m+n),后续补充。

Python实现:
class Solution:
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        haylen = len(haystack)
        needlen = len(needle)
        if needlen == 0:
            return 0
        if haylen < needlen:
            return -1
        i = 0; j = 0; count = 0;
        while i < haylen:
            if j < needlen and haystack[i] == needle[j]:
                j += 1
                count += 1
            elif count > 0 and haystack[i] != needle[j]:  # needle从头开始比较
                j = 0  
                i -= count  # 回退count个字符
                count = 0
            i += 1  
            if count == needlen:
                return i - count
        return -1

a = "ississip"
b = "issip"
c = Solution()
print(c.strStr(a,b))  # 3
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 今天被“18岁”刷屏了,很多人都有共鸣发出自己18青涩的样子,不仅仅是怀念那个年龄很美好,怀念满脸的胶原蛋白,更多...
    砂糖酱阅读 824评论 0 0
  • 昼夜干咳指枯黄,口臭齿褐肺油黑。 瘾来自力怎把持,瘾去戒止如抽丝。
    曾良知阅读 203评论 0 0
  • 秋风瑟瑟秋草黄 贪黑起早整天忙 只晓它乡风光美 不见家乡丰收忙 庭院红果枝头挂 没有时间去品尝 一缕秋思寄冷月 浊...
    沧海桑田_bc60阅读 171评论 0 1

友情链接更多精彩内容