leetcode 28(简单kmp)
void GetNext(string &needle,int next[]) { next[0]=-1; int k=-1; int len=needle.size(); for(int i=1;i<len;i++) { while(k!=-1&&needle[k+1]!=needle[i]) k=next[k]; if(needle[k+1]==needle[i]) { k++; } next[i]=k; } } int strStr(string haystack, string needle) { int nlen=needle.size(); int hlen=haystack.size(); if(nlen==0) return 0; if(hlen==0) return -1; int *next=new int[nlen]; GetNext(needle,next); int k=-1; for(int i=0;i<hlen;i++) { while(k!=-1&&needle[k+1]!=haystack[i]) k=next[k]; if(needle[k+1]==haystack[i]) { k++; if(k==nlen-1) return i-k; } } return -1; }
posted on 2020-03-09 18:24 QingFengDaHui 阅读(218) 评论(0) 编辑 收藏 举报