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代码见:

  1. class Solution {
  2. public:
  3. int strStr(char *haystack, char *needle) {
  4. int num = strlen(needle);
  5. int *next = new int[num];
  6. getNext(needle, next);
  7.  
  8. int i = ;
  9. int j = ;
  10. while (haystack[i] != '\0' && needle[j] != '\0') {
  11. if (haystack[i] == needle[j]) {
  12. ++i;
  13. ++j;
  14. } else if (j == ) {
  15. ++i;
  16. } else {
  17. j = next[j - ];
  18. }
  19. }
  20.  
  21. free(next);
  22. if (needle[j] != '\0')
  23. return -;
  24. else
  25. return i - j;
  26. }
  27.  
  28. void getNext(char *needle, int *next) {
  29. int i = ;
  30. int j = ;
  31. next[] = ;
  32. while (needle[i] != '\0') {
  33. if (needle[i] == needle[j]) {
  34. next[i] = j + ;
  35. ++i;
  36. ++j;
  37. } else if (j == ) {
  38. next[i] = ;
  39. ++i;
  40. } else {
  41. j = next[j - ];
  42. }
  43. }
  44. }
  45. };

代码优化:

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

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

AC代码如下:

  1. class Solution {
  2. public:
  3. int strStr(char *haystack, char *needle) {
  4. int num = strlen(needle);
  5. int *next = new int[num];
  6. getNext(needle, next);
  7.  
  8. int i = ;
  9. int j = ;
  10. while (haystack[i] != '\0' && j < num) {
  11. if (j == - || haystack[i] == needle[j]) {
  12. ++i;
  13. ++j;
  14. } else {
  15. j = next[j];
  16. }
  17. }
  18.  
  19. free(next);
  20. if (needle[j] != '\0')
  21. return -;
  22. else
  23. return i - j;
  24. }
  25.  
  26. void getNext(char *needle, int *next) {
  27. int i = ;
  28. int j = -;
  29. int strl = strlen(needle);
  30. next[] = -;
  31. while (i < strl - ) {
  32. if (j == - || needle[i] == needle[j]) {
  33. next[++i] = ++j;
  34. } else {
  35. j = next[j];
  36. }
  37. }
  38. }
  39. };

【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. c# post get

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  2. Codeforces - 617E 年轻人的第一道莫队

    我对莫队算法最为纠结的地方就是区间端点处,应该是像代码里那样理解吧 cnt[i]表示i出现的次数 maxn开2e6比较保险 /*H E A D*/ struct Query{ int l,r,id; ...

  3. Oracle9i之xmltype应用(2)

    Oracle 9i提供的XML内置特性: Oracle 9i支持XMLType类型,它是一种Oracle 9i系统定义的对象类型.XMLType有内置的函数,有力的提供了推XML的创建,索检,索引等功 ...

  4. pandas强化练习

    这篇文章写得更好:http://wittyfans.com/coding/%E5%88%A9%E7%94%A8Pandas%E5%88%86%E6%9E%90%E7%BE%8E%E5%9B%BD%E4 ...

  5. Scrapy安装指南(windows)

    windows开发,难免遇到很多坑,比一般开发是艰苦得多.先不吐槽windows,我们直接看这个scrapy怎么安装. 首先,要有一份文档,比如我用这个: http://scrapy-chs.read ...

  6. aoj0558

    一.题意: 在H * W的地图上有N个奶酪工厂,分别生产硬度为1-N的奶酪.有一只吃货老鼠准备从老鼠洞出发吃遍每一个工厂的奶酪.老鼠有一个体力值,初始时为1,每吃一个工厂的奶酪体力值增加1(每个工厂只 ...

  7. hcheck 脚本

    hcheck.sql - Script to Check for Known Problems in Oracle8i, Oracle9i, Oracle10g, Oracle 11g and Ora ...

  8. ajax请求方法及参数说明

    $.ajax()请求示例 <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> ...

  9. 爬虫beautifulsoup实践

    爬虫beautifulsoup实践: 目的:在https://unsplash.com/上爬取图片并保存到本地文件夹里.   一.观察response.首先,在Chrome浏览器里观察一下该网页的re ...

  10. Missing artifact com.oracle:ojdbc6:jar:11.2.0.1.0问题解决 ojdbc包pom.xml出错

    <!-- 添加oracle jdbc driver --> <dependency> <groupId>com.oracle</groupId> < ...