c++实现的kmp算法

    int strStr(string haystack, string needle) {
        if (needle.length() == 0){
            return 0;
        }
        int next[needle.length()];
        getNext(needle,next);

        int i = 0,j = 0;
        while( i < (int)haystack.length() && j < (int)needle.length()&&(i - j) <(int)(haystack.length()-needle.length())+1 ){

            if ( j == -1 ||haystack[i] == needle[j]){
                j++;
                i++;
            } else{
                j = next[j];
            }
        }
        if (j == needle.length()){
            return i-needle.length();
        } else{
            return -1;
        }

    }
    void getNext(string needle,int next[]){
        int j = 0;
        int k = -1;

        next[0]=-1;

        while (j< needle.length()){
            if (k == -1 || needle[j] == needle[k]){
                ++j;
                ++k;
                next[j]=k;
            
//                if (needle[j] != needle[k]){
//                    next[j] = k;
//                } else{
//                    next[j] = next[k];
//                }

            } else{
                k = next[k];
            }
        }
    }

你可能感兴趣的:(c++实现的kmp算法)