前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q28 Implement strStr()

Q28 Implement strStr()

作者头像
echobingo
发布2018-04-25 16:37:52
5230
发布2018-04-25 16:37:52
举报

Implement strStr().

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

Example 1:
代码语言:javascript
复制
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
代码语言:javascript
复制
Input: haystack = "aaaaa", needle = "bba"
Output: -1
解题思路:

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

注意点:

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

Python实现:
代码语言:javascript
复制
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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.02.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Example 1:
  • Example 2:
  • 解题思路:
  • 注意点:
  • Python实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档