字符串匹配

来源:互联网 发布:男性卫生知况 编辑:程序博客网 时间:2024/05/29 14:28

Implement strStr().

Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Subscribe to see which companies asked this question
28. Implement strStr()

KMP算法


class Solution {public:    void makeNext(string needle,int next[]){        int k=0,j;        next[0]=-1;        for(j=0;j<=needle.length();j++){            while(k>0&&needle[k]!=needle[j]){                k=next[k];            }            if(j>0&&needle[k]==needle[j]){                k++;            }            next[j+1]=k;        }    }    int strStr(string haystack, string needle) {        int length=needle.length();        int next[length+1];        makeNext(needle,next);        if(length==0){            return 0;        }        int q=0;        for(int i=0;i<haystack.length();i++){            while(q>0&&haystack[i]!=needle[q]){                q=next[q];            }            if(q<=length-1&&haystack[i]==needle[q]){                q++;            }            if(q==length){                return i-q+1;            }            //q=next[q];        }        return -1;    }};
0 0