爱写bug(ID:icodebugs)

作者:爱写bug

实现 strStr() 函数。

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

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

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().

说明:

needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与C语言的 strstr() 以及 Java的 indexOf() 定义相符。

解题思路(Java):

  • 暴力穷举:

    复杂度:时间 O(n^2) 空间 O(1)

    字符串 a 从第一个索引开始 逐一匹配字符串 b 的第一个索引:a[i++]==b[0],如果为true,则进入内循环字符串a从第 i+j 个字符开始与字符串b 第 j个字符匹配:a[i+j]==b[j]

代码:
class Solution {
public int strStr(String haystack, String needle) {
if(needle.equals(""))return 0;
int haystackLen=haystack.length(),needleLen=needle.length();
char firstChar=needle.charAt(0);

for(int i=0;i
  • KMP算法:
    复杂度:时间 O(n+m) 空间 O(M) 下面引用一组图片帮助理解(图片来源:https://blog.csdn.net/v_july_v/article/details/7041827 ): 说明: 图片中字符串haystack为:"BBC ABCDAB ABCDABCDABDE",模式串 needle 为:"ABCDABD"
    第一步开始匹配: 第二步匹配到第一个相同字符: 第三步两个字符串逐一向后匹配,直到到字符 D 与 空格 字符匹配失败,结束该轮次匹配: 第四步重新匹配,但不用从第二步的下一个字符 B 开始,因为空格字符前与模式字符串前6个字符已经匹配相同。既C字符之前的两个字符 AB 与空格字符前两个字符 AB 相同,两个字符串可直接从 空白 字符与 C 字符开始匹配:
    可以看到图片中一下跳过了 haystack 五个字符ABCDAB 和 needle 的两个字符AB。优化思路很清晰。
代码:
class Solution {
public int strStr(String haystack, String needle) {
if(needle.equals("")) return 0;
int[] next = new int[needle.length()];
getNext(next, needle);// 得到next数组
// i是匹配串haystack的指针,j是模式串needle的指针
int i = 0, j = 0;
while(i

总结:

KMP算法优化的方向很明了,主要难点就在于对next数组的求法和理解,KMP算法不是本文的重点,如有兴趣深入了解,推荐一篇博文:https://blog.csdn.net/v_july_v/article/details/7041827 另外还有Sunday算法 是找到与模式字符串相同长度的源字符串 从右向左匹配,其中心思想为:
  • 如果该字符没有在模式串中出现,直接从该字符向右移动位数 = 模式串长度 + 1。(因为源字符串含有该字符的相同长度字符串不可能匹配)
  • 如果该字符在模式串中出现过,其移动位数 = 模式串中最右端的该字符到末尾的距离+1。
字符串haystackBBC ABC 与模式串needle ABCDABD 匹配,字符串haystack中的空格字符未在模式串needle 中出现,则可以直接跳过空格字符后面六个字符的匹配,因为包含空格字符的相同长度字符串都不可能匹配成功,所以可以跳过6个。

Python3:

说明:上面两种方法在所有语言都可行,只是语法不同,所以在py3中不再复现,仅展示一些py3特有的语法投机取巧解题。 利用py3内建函数find()直接得结果。
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
return haystack.find(needle)
find() 方法描述

find() 方法检测字符串中是否包含子字符串 str ,如果指定 beg(开始) 和 end(结束) 范围,则检查是否包含在指定范围内,如果指定范围内如果包含指定索引值,返回的是索引值在字符串中的起始位置。如果不包含索引值,返回-1。如果子字符串为空,返回0。

语法
str.find(str, beg=0, end=len(string))
参数
  • str -- 指定检索的字符串

  • beg -- 开始索引,默认为0。

  • end -- 结束索引,默认为字符串的长度。

利用py3字符出切片特性解决:

class Solution:
def strStr(self, haystack: str, needle: str) -> int:
for i in range(len(haystack)-len(needle)+1):
if haystack[i:i+len(needle)]==needle:#截取切片
return i
return -1

注:算法导论第32章:字符串匹配有完整的一章相关讨论。

LeetCode 28:实现strStr() Implement strStr()的更多相关文章

  1. LeetCode专题-Python实现之第28题: Implement strStr()

    导航页-LeetCode专题-Python实现 相关代码已经上传到github:https://github.com/exploitht/leetcode-python 文中代码为了不动官网提供的初始 ...

  2. Leetcode 详解(Implement strstr)

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

  3. leetcode第27题--Implement strStr()

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

  4. [Swift]LeetCode28. 实现strStr() | Implement strStr()

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

  5. 【LeetCode算法-28/35】Implement strStr()/Search Insert Position

    LeetCode第28题 Return the index of the first occurrence of needle in haystack, or -1 if needle is not ...

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

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

  7. 44. leetcode 28. Implement strStr()

    28. Implement strStr() Implement strStr(). Returns the index of the first occurrence of needle in ha ...

  8. C# 写 LeetCode easy #28 Implement strStr()

    28.Implement strStr() Implement strStr(). Return the index of the first occurrence of needle in hays ...

  9. 【LeetCode】28. Implement strStr() (2 solutions)

    Implement strStr() Implement strStr(). Returns a pointer to the first occurrence of needle in haysta ...

随机推荐

  1. ABP中文网的一些BUG

    之前一些翻译了的文档没有及时更新.比如 IAsyncCrudAppService接口在很久之前的版本就已经改为了ICrudAppService,如果是在官网下载的最新实例中IAsyncCrudAppS ...

  2. DesignPattern系列__07合成复用原则

    基本介绍 合成复用原则的核心,就是尽量去使用组合.聚合等方式,而不是使用继承. 核心思想 1.找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起. 2.针对接口编程,而不是 ...

  3. CSS函数大全

    CSS函数(方法)参考 CSS函数用作各种CSS属性的值. 函数 描述 attr() 返回所选元素的属性值 calc() 允许您执行计算以确定CSS属性值 cubic-bezier() 定义Cubic ...

  4. Vue--运行项目发送http://localhost:8080/sockjs-node/info请求报错,造成浏览器不能热更新

    今早习惯打开vscode 输入 npm run dev 准备修复测试提出的bug 不料一堆通红的报错,让人感到有点绿的慌. 有问题呢,就需要解决问题.经过一番排查后发现是我昨天为了让测试在我本地项目中 ...

  5. vue如何导入外部js文件(es6)

    也许大家都是使用习惯了es5的写法喜欢直接用<Script>标签倒入js文件,但是很是可惜,这写法.在es6,或则说vue环境下不支持 真的写法是怎样? 首先.我们要改造我们要映入的外部j ...

  6. MySQL Tools 之 mysql.server 脚本运用

    MySQL distributions on Unix and Unix-like system include a script named mysql.server, which starts t ...

  7. SpringBoot的学习一:入门篇

    SpringBoot是什么: SpringBoot是Spring项目中的一个子工程,是一个轻量级框架. SpringBoot框架中有两个个非常重要的策略:开箱即用和约定优于配置 一.构建工程 1.开发 ...

  8. 数据库操作之DBUtils

    概述 DBUtils是Java编程中的数据库操作实用工具,小巧简单实用. DBUtils封装了对JDBC的操作,简化了JDBC操作,可以少写代码. DBUtils三个核心功能介绍 QueryRunne ...

  9. 09、日志轮转+rsync同步

    logrotate   -  rotates,  compresses,  and    mails system logs 日志轮转 rotate 日志切割 轮转   切割   备份   归档 常见 ...

  10. 机器学习(4)——PCA与梯度上升法

    主成分分析(Principal Component Analysis) 一个非监督的机器学习算法 主要用于数据的降维 通过降维,可以发现更便于人类理解的特征 其他应用:可视化.去噪 通过映射,我们可以 ...