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. 选择排序 Selection Sort

    选择排序 Selection Sort 1)在数组中找最小的数与第一个位置上的数交换: 2)找第二小的数与第二个位置上的数交换: 3)以此类推 template<typename T> / ...

  2. bzoj1079 着色方案 记忆化搜索(dp)

    题目传送门 题目大意: 有k种颜色,每个颜色ci可以涂个格子,要求相邻格子颜色不能一样,求方案数.ci<=5,k<=15. 思路: 题目里最重要的限制条件是相邻格子颜色不能相同,也就是当前 ...

  3. Tyvj - 1305 单调队列优化dp

    今天有点头痛就不写具体细节了,贴完走人 #include<iostream> #include<algorithm> #include<cstdio> #inclu ...

  4. c# 实现无符号右移

    /// <summary> /// 无符号右移, 相当于java里的 value>>>pos /// </summary> /// <param nam ...

  5. Mac上Node环境配置

    公司配备Mac笔记本,以前没用过mac开发项目,一开始依然是从node官网下载安装包,后来领导说最好是用brew安装软件,这样比较方便,安装和卸载,只要在命令行输入相应的 install 和 unin ...

  6. Nginx + Lua搭建文件上传下载服务

    收录待用,修改转载已取得腾讯云授权 最新腾讯云技术公开课直播,提问腾讯W3C代表,如何从小白成为技术专家?点击了解活动详情 作者 | 庄进发 编辑 | 迷鹿 庄进发,信息安全部后台开发工程师,主要负责 ...

  7. Mina入门demo

    初识Mina,简要记录理解内容和实现demo. 这里先简述一下BIO和NIO的区别: 同步阻塞IO(BIO):一个连接一个线程,客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任 ...

  8. 防盗链与springboot代理模式(图片文件转发)

    在搭建自己的博客网站的时候,很有可能要引入一些外部图片,毕竟多数人最开始不是在自己的平台上写博客. 因某种需要,搬运自己以前写的博客到自己的网站时,在图片这一步可能会出现问题,无法显示.其中往往就是防 ...

  9. 【c#文档】在 C# 中,(int) ,Int32.Parse() 和 Convert.toInt32() 三种方法的区别

    [c#文档]https://msdn.microsoft.com/zh-cn/library/system.convert.toint32.aspx 转载自:http://www.cnblogs.co ...

  10. 你还在把Java当成Android官方开发语言吗?Kotlin了解一下!

    导语:2017年Google IO大会宣布使用Kotlin作为Android的官方开发语言,相比较与典型的面相对象的JAVA语言,Kotlin作为一种新式的函数式编程语言,也有人称之为Android平 ...