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. Map, filter and reduce

    To add up all the numbers in a list, you can use a loop like this: Total is initialized to 0. Each t ...

  2. Linux-php安装mongodb

    Linux-php安装mongodb 标签(空格分隔): php 安装mongodb 1 下载解压 下载压缩包 :https://www.mongodb.com/download-center?jmp ...

  3. 7.stack

    #include <iostream> #include <stack> #include <algorithm> #include <list> #i ...

  4. The evolution of cluster scheduler architectures--转

    原文地址:http://www.firmament.io/blog/scheduler-architectures.html cluster schedulers are an important c ...

  5. Java Web应用定制404错误页面

    Http响应状态码404的含义是服务器端没有找到客户端请求的资源,定制404错误页面至少有以下两个好处: 1.向客户端隐藏服务器信息,服务器提供的默认404错误页面上一般都包含当前应用使用的是什么服务 ...

  6. 双列集合Map的嵌套遍历

    双列集合Map的嵌套使用,例如HashMap中还有一个HashMap,这样的集合遍历起来稍微有点儿复杂.例如一个集合:HashMap<Integer,HashMap<String,Inte ...

  7. NodeJS学习笔记 进阶 (2)Nodejs进阶:MD5加密算法(ok)

    个人总结:这篇文章讲解了Nodejs中自带模块的MD5加密算法的使用,读完这篇文章需要15分钟,其实还有一个叫utility的包在npm上,也非常好用. 摘选自网络 简介 MD5(Message-Di ...

  8. iOS——扬声器与听筒的切换

    1.扬声器模式:  NSError *error; [[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPor ...

  9. TP5 belongsTo 和 hasOne的区别

    hasOne和belongsTo这两种方法都可以应用在一对一关联上,但是他们也是有区别的: belongsTo: 从属关系:就是谁为主的问题 A:{id,name,sex} B:{id,name.A_ ...

  10. POJ——T 2449 Remmarguts' Date

    http://poj.org/problem?id=2449 Time Limit: 4000MS   Memory Limit: 65536K Total Submissions: 30754   ...