leetcode28. 实现 strStr()

28. 实现 strStr()

题目链接:28. 实现 strStr()

题目描述

实现 strStr() 函数。

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

  • 0 <= haystack.length, needle.length <= 5 * 10 4
  • haystackneedle 仅由小写英文字符组成

思路分析

字符串匹配问题,KMP算法。kmp算法详细讲解:https://www.zhihu.com/question/21923021

kmp算法本质是利用模式串的公共前后缀信息来加速匹配过程,暴力的匹配思路是对于主串的每一个字符作为起点进行匹配,查看是否有满足的。kmp则是跳过了一些不可能出现匹配情况从而加速匹配。kmp算法的核心是求next数组,next数组保存的是模式串的公共前后缀信息。

代码实现

class Solution {
public:
    int strStr(string haystack, string needle) {
        int slen=needle.size();
        int tlen=haystack.size();
        if(!slen)
            return 0;
        vector<int>next(slen);
        //构建next数组
        next[0]=-1;
        for(int i=1,j=-1;i<slen;i++)
        {
            while(j>-1&&needle[j+1]!=needle[i])j=next[j];
            if(needle[j+1]==needle[i])j++;
            next[i]=j;
        }
        //匹配过程
        for(int i=0,j=-1;i<tlen;i++)
        {
            while(j>-1&&haystack[i]!=needle[j+1]) j=next[j];
            if(haystack[i]==needle[j+1])j++;
            if(j==needle.size()-1)
                return i-needle.size()+1;
        }
        return -1;
    }
};
posted @ 2021-07-15 10:44  曾凡璐  阅读(40)  评论(0)    收藏  举报