Implement strStr().

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

解题:

本题为典型的KMP算法考察题,KMP算法描述为:

  设主串S,匹配串P,i为S的索引下标,j为P的索引下标,初始i和j设置为0。

  在i小于S的长度和j小于P的长度时,开始循环:

  1、比较S[i]和P[j]是否相同;

  2、如果相同则i++,j++,返回执行第1步;

  3、如果不同,则计算已匹配成功的P[0]~P[j-1]中,相同前缀和后缀的最大长度,设为n;

  4、令i不变,j为n(指向相同前后缀的后一个字符),返回执行第1步;

  循环结束时,查看j值是否等于P的长度,如果等于则匹配成功,否则主串中不包含匹配串。

计算最长相同前后缀:

  新建一个数组a,数组长度为匹配串P长度。数组的每一位a[i],表示由P[0]~P[i]表示的字符串,最长相同前后缀的位数;

  a[0]初始化为0,令i为1,j为0,对于a[i](0<i<len)有两种情况:

  1、如果P[j] == P[i],那么a[i] = a[i - 1] + 1;

     接着j++,i++重新执行第一步;

  2、当P[j] != P[i],如果j此时为0,表示由P[0]~P[i]组成的字符串没有相同的前缀和后缀,所以a[i]=0,i++继续进行第一步;

  3、当P[j] != P[i],并且j不为0,表示可能包含相同前缀和后缀,则令j = a[j - 1],继续执行第一步;

  直到计算出所有a[i]的值。

AC代码见:

 class Solution {
public:
int strStr(char *haystack, char *needle) {
int num = strlen(needle);
int *next = new int[num];
getNext(needle, next); int i = ;
int j = ;
while (haystack[i] != '\0' && needle[j] != '\0') {
if (haystack[i] == needle[j]) {
++i;
++j;
} else if (j == ) {
++i;
} else {
j = next[j - ];
}
} free(next);
if (needle[j] != '\0')
return -;
else
return i - j;
} void getNext(char *needle, int *next) {
int i = ;
int j = ;
next[] = ;
while (needle[i] != '\0') {
if (needle[i] == needle[j]) {
next[i] = j + ;
++i;
++j;
} else if (j == ) {
next[i] = ;
++i;
} else {
j = next[j - ];
}
}
}
};

代码优化:

实际编写中,为了避免判定j是否为0,简化操作。可以设定next数组,取代a数组。next的含义是,当kmp算法需要寻找子串下一个比较的位置时,直接从next数组中取值;

其中next[0] = -1作为哨兵位,next[i] = a[i - 1],即将a数组整体后移一位保存在next数组中。

AC代码如下:

 class Solution {
public:
int strStr(char *haystack, char *needle) {
int num = strlen(needle);
int *next = new int[num];
getNext(needle, next); int i = ;
int j = ;
while (haystack[i] != '\0' && j < num) {
if (j == - || haystack[i] == needle[j]) {
++i;
++j;
} else {
j = next[j];
}
} free(next);
if (needle[j] != '\0')
return -;
else
return i - j;
} void getNext(char *needle, int *next) {
int i = ;
int j = -;
int strl = strlen(needle);
next[] = -;
while (i < strl - ) {
if (j == - || needle[i] == needle[j]) {
next[++i] = ++j;
} else {
j = next[j];
}
}
}
};

【Leetcode】【Easy】Implement strStr()的更多相关文章

  1. 【LeetCode题意分析&解答】40. Combination Sum II

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  2. 【LeetCode题意分析&解答】37. Sudoku Solver

    Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...

  3. 【LeetCode题意分析&解答】35. Search Insert Position

    Given a sorted array and a target value, return the index if the target is found. If not, return the ...

  4. 【leetcode刷题笔记】Implement strStr()

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

  5. ACM金牌选手整理的【LeetCode刷题顺序】

    算法和数据结构知识点图 首先,了解算法和数据结构有哪些知识点,在后面的学习中有 大局观,对学习和刷题十分有帮助. 下面是我花了一天时间花的算法和数据结构的知识结构,大家可以看看. 后面是为大家 精心挑 ...

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

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

  7. 【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 ...

  8. 【LeetCode算法题库】Day4:Regular Expression Matching & Container With Most Water & Integer to Roman

    [Q10] Given an input string (s) and a pattern (p), implement regular expression matching with suppor ...

  9. 【LeetCode算法题库】Day7:Remove Nth Node From End of List & Valid Parentheses & Merge Two Lists

    [Q19] Given a linked list, remove the n-th node from the end of list and return its head. Example: G ...

  10. 【LeetCode算法题库】Day3:Reverse Integer & String to Integer (atoi) & Palindrome Number

    [Q7]  把数倒过来 Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Outpu ...

随机推荐

  1. 建立ionic3的环境

    看了好些例子,关于如何搭建ionic3的环境的,结果因为代理服务器的原因,弄好久才成功.前面的步骤网上随意可以找到的了,关键是ionic设置代理的地方,如果你的公司也需要代理才能到外网的话.... 1 ...

  2. 【总结】kali(amd64)中安装nessus

    下载nessus: http://www.tenable.com/products/nessus/select-your-operating-system 注册nessus家庭版 http://www ...

  3. Python——爬取瓜子二手车

    # coding:utf8 # author:Jery # datetime:2019/5/1 5:16 # software:PyCharm # function:爬取瓜子二手车 import re ...

  4. 多租户概念以及FreeLink多租户设计思想

    多租户实现思想 多租户技术的实现重点,在于不同租户间应用程序环境的隔离(application context isolation)以及数据的隔离(data isolation),以维持不同租户间应用 ...

  5. rancher初级(搭建+基本操作+web应用部署)

    Rancher搭建 首先rancher需要安装了docker的linux环境,我的系统版本为 在docker的基础上启动rancher服务器,Rancher 服务器是一个 Docker image,所 ...

  6. Angular4+NodeJs+MySQL 入门-04 接口调用类

    上一篇文章说一下,后台接口的创建,这篇说一下如果调用接口. 创建一个目录helpers 此目录下有三个文件分别是 ApiClient.ts.clientMiddleware.ts.Core.ts,前面 ...

  7. 安装cloudermanager时出现org.spingframework.web.bind.***** host[] is not present at AnnotationMethodHandlerAdapter.java line 738 ****错误(图文详解)(博主推荐)

    不多说,直接上干货! 首先,这个问题,写给需要帮助的朋友们,本人在此,搜索资料近半天,才得以解决.看过国内和国外,资料甚少.特此,写此博客,为了弥补此错误解决的资料少的缘故! 问题详解  解决办法   ...

  8. 最好用的数据存储Easy Save2讲解

    转载:http://www.manew.com/thread-100109-1-1.html   今天抽时间学习了“Easy Save2”插件,版本v2.6.3  我个人觉得这个插件是做数据存取最好的 ...

  9. Kubernetes系列:(1) 初探

    1. 背景 在部门内容组织了一次K8s的培训,普及了下K8s的概念.框架.操作等,为便于后期查阅,也为了进一步深究K8s,因此开展K8s系列,周期不定- 2. 概念 (1) 含义:来自希腊语,意为&q ...

  10. ubuntu命令行添加拥有管理员权限新用户

    最近买了个服务器,只有一个root用户,天天登录挺不方便的,所以想要新建用户;之前在本地都是用界面话新建的用户,这次记录一下学习命令行新建用户的过程: 第一步 : # sudo adduser zhq ...