LeetCode28. 实现 strStr() [简单]——KMP、next[]

题目描述:

我的解题:

本来KMP算法的东西都忘了,通过这道题复习了一下

其中计算next的循环while(i<length-1),注意需要-1,因为下面有i++,否则会报错

在这里花了好长时间找错

class Solution {
//private:
  //  int next[];
public:
    int* func(string needle){
        int* next=new int[needle.length()];
        int length=needle.length();
        int i=0;
        int j=-1;
        next[0]=-1;
        while(i<length-1){
            if(j==-1 || needle[i]==needle[j]){
                i++;
                j++;
                next[i]=j;
            }
            else    j=next[j];
        }
        return next;
    }
    int strStr(string haystack, string needle) {
        if(needle=="")  return 0;
        if(haystack==""&&needle!="")    return -1;
        if(haystack.length()<needle.length())   return -1;
        int *next=func(needle);
        int i=0,j=0;
        int la=(int)haystack.length(),lb=(int)needle.length();
        while(i<la&&j<lb){
            if(j==-1 || haystack[i]==needle[j]){
                i++;
                j++;
            }
            else    j=next[j];
        }
        return j==lb?i-j:-1;
    }
};

发布了66 篇原创文章 · 获赞 1 · 访问量 504

猜你喜欢

转载自blog.csdn.net/qq_41041762/article/details/105153527