LeetCode——实现strstr()

题目地址:https://leetcode-cn.com/problems/implement-strstr/

解题思路:KMP算法。该题注意的是string类的size()方法返回的是无符号的值。

     简单说一下KMP算法。KMP算法就是在暴力匹配的算法中引入next数组,匹配的时候如果不匹配只更新模式串中j的值。

       next[j]数组表示的是模式串p中前j-1个字符串的最长前后缀长度。i指向p的后缀,j指向p的前缀,next[i]=j;

      • 若p[j]=p[i],next[i+1]=next[i]+1;
      • 否则,j=next[j]。我的理解:当不相等的时候说明next[i+1]的最长前后缀长度肯定不是next[i]+1(j+1),也就是说要从j的前面重新去找,由于前面与j匹配的前缀是next[j],所以与i匹配的前缀在字符串0...next[j]中。
class Solution {
private:
    int *next;
    void getNext(string needle){
        unsigned long len=needle.size();
        next=new int[len+1];
        int i=0,j=-1;//i指向p后缀,j指向前缀
        next[0]=j;
        while (i<len) {
            if(j==-1||needle[i]==needle[j])
                next[++i]=++j;
            else
                j=next[j];
        }
    }
public:
    int strStr(string haystack, string needle) {
        getNext(needle);
        int i=0,ans=-1,j=0;
        if(needle=="")
            return 0;
        if(needle.size()==1)
            return haystack.find(needle);
        while (i<(int)haystack.size()&&j<(int)needle.size()) {
            if(j==-1){
                j=0;
                i++;
            }
            if(haystack[i]==needle[j]){
                i++;
                j++;
            }
            else
                j=next[j];
        }
        if(j==needle.size())
            ans=i-j;
        return ans;
    }
};

 

posted @ 2020-10-15 21:02  CCxiao5  阅读(99)  评论(0编辑  收藏  举报