您的位置:首页 > 其它

【算法】字符串匹配问题

2017-02-14 03:59 302 查看
28. Implement strStr()

KMP算法

KMP算法我觉得KMP算法的Next数组详解这篇文章讲的还是非常的透彻的。

vector<int> next;
void getnext(const string &needle){
next[0] = -1;
int i = 0,k = -1;
//还要注意这个地方,不要漏了后面那个-1
while(i<needle.size()-1){
if(k == -1 || needle[i] == needle[k])
next[++i] = ++k;
else
k = next[k];
}
}
int kmp(const string& haystack,const string& needle){
int i = 0,j = 0;
//注意一下这个地方的神坑点就行,size()函数返回的是unsigned类型,做类型比较的话,当j=-1时,会将j变为unsigned的类型,然后判断出j>needle.size(),从而不进入判断。
while(i<haystack.size()&&(j==-1||j<needle.size())){
if(j == -1 || haystack[i] == needle[j]){
i++;
j++;
}else{
j = next[j];
}
}
if(j == needle.size())
return i-j;
return -1;
}
int strStr(string haystack, string needle) {
if(needle.size() == 0)
return 0;
next = vector<int> (needle.size(),0);
getnext(needle);
return kmp(haystack,needle);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 kmp