LeetCode解题之Implement strStr()


原题

实现字符串子串匹配函数strStr()。

假设字符串A是字符串B的子串。则返回A在B中首次出现的地址。否则返回-1。

注意点:

- 空字符串是全部字符串的子串,返回0

样例:

输入: haystack = “abc”, needle = “bc”

输出: 1

输入: haystack = “abc”, needle = “gd”

输出: -1

解题思路

字符串匹配常见的算法是KMP。只是感觉该算法理解困难,效率也不是特别高。

我用了Sunday算法来实现字符串的匹配。大体思路例如以下:

被搜索的字符串是”abcdefg”,要搜索的字符串是”ef”

 abcdefg
ef

假设当前不匹配,则推断当前尝试匹配的后一位。即”c”是否在要搜索的字符串中,假设不在,则要搜索的字符串直接后移它自己的长度+1。

 abcdefg
ef

假设存在,如此时”f”在”ef”中,则把该位置对齐。

 abcdefg
ef

匹配成功返回结果。

AC源代码

class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
if not haystack:
return -1
i = 0
needleLength = len(needle)
while i < len(haystack):
if haystack[i:i + needleLength] == needle:
return i
else:
index = 0
try:
index = needle.rindex(haystack[i + needleLength])
except Exception:
i += needleLength + 1
i += needleLength-index
return -1 if __name__ == "__main__":
assert Solution().strStr("abcdefg", "ab") == 0
assert Solution().strStr("abcdefg", "bc") == 1
assert Solution().strStr("abcdefg", "cd") == 2
assert Solution().strStr("abcdefg", "fg") == 5
assert Solution().strStr("abcdefg", "bcf") == -1

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源代码。

LeetCode Implement strStr()(Sunday算法)的更多相关文章

  1. [Leetcode] implement strStr() (C++)

    Github leetcode 我的解题仓库   https://github.com/interviewcoder/leetcode 题目: Implement strStr(). Returns ...

  2. [LeetCode] Implement strStr() 实现strStr()函数

    Implement strStr(). Returns the index of the first occurrence of needle in haystack, or -1 if needle ...

  3. LeetCode: Implement strStr() [027]

    [题目] Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if ...

  4. leetcode——Implement strStr() 实现字符串匹配函数(AC)

    Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if need ...

  5. [LeetCode] Implement strStr()

    Implement strStr(). Returns a pointer to the first occurrence of needle in haystack, or null if need ...

  6. leetcode implement strStr python

    #kmp class Solution(object): def strStr(self, haystack, needle): """ :type haystack: ...

  7. LeetCode Implement strStr() 实现strstr()

    如题 思路:暴力就行了.1ms的暴力!!!别的牛人写出来的,我学而抄之~ int strStr(char* haystack, char* needle) { ; ; ; ++i) { ; ; ++j ...

  8. 第3章:LeetCode--算法:strStr KMP算法

    https://leetcode.com/problems/implement-strstr/  28. Implement strStr() 暴力算法: int ViolentMatch(char* ...

  9. [Leetcode][Python]28: Implement strStr()

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 28: Implement strStr()https://oj.leetco ...

随机推荐

  1. rest_framework-认证-总结完结篇

    执行过程 APIView() Ruquest() Authentication() OrderView()APIView() def duspatch: self.initial(request) d ...

  2. Dictionaries

    A dictionary is like a list, but more general. In a list, the indices have to be integers; in a dict ...

  3. Square roots

    Loops are often used in programs that compute numerical results by starting with an approximate answ ...

  4. CUDA笔记(八)

    今天真正进入了攻坚期.不光是疲劳,主要是遇到的问题指数级上升,都是需要绕道的. 以visual profile来说,刚刚发现自己还没使用过. http://bbs.csdn.net/topics/39 ...

  5. 使用HANDLECOLLISIONS的几个场景

    使用HANDLECOLLISIONS的几个场景: 1.target丢失delete记录(missing delete),忽略该问题并不记录到discardfile 2.target丢失update记录 ...

  6. mongodb 主从

    mongodb 主从 因为条件限制我们把主从放在一台服务器上面 相关参数 在启动从的时候可以增加以下参数 --autoresync 当发现从服务器的数据不是最新时,开始从主服务器请求同步数据 --sl ...

  7. tensorflow 1 - 起步

    使用图 (graph) 来表示计算任务. 在被称之为 会话 (Session) 的上下文 (context) 中执行图. 使用 tensor 表示数据. 通过 变量 (Variable) 维护状态. ...

  8. php八大设计模式之适配器模式

    将一个抽象被具体后的结果转换成另外一个需求所需的格式. 在生活中也处处有适配器的出现,比如转换头,就是让两种不同的规格合适的搭配在一起. <?php header("content-t ...

  9. [JSOI2007]文本生成器(AC自动机+DP)

    题意 给你n个串.问有多少长度为m的串使得这n个串至少在其中出现过一次.输出答案膜10007意义下的结果. (n<=100,每个串的长度<=100) 题解 在AC自动机上跑DP. 用到一个 ...

  10. easyui-combobox实现取值范围的联动

    需求:需要用两个combobox来输入一个年月的范围,下拉框的内容从服务器获取.需要实现选中前者后,后者的下拉框中不能显示比前者数值小的:选中后者后,前者的下拉框内容不能显示比后者数值大的 有两个co ...