前两篇文章是从网上搜索的,知道了next数组可以有多种表示方法,但感觉KMP算法详解里面第二种表示法给的程序有点小问题,今天自己改进了下,然后在leetcode(strStr)上验证了下,发现自己改进的程序可以AC,证明没有问题
现在在这篇博客中总结蛮力、KMP、BM算法的各种AC解法:
蛮力法:耗时6ms(cpp)
class Solution {
public:
int strStr(string haystack, string needle) {
int len1 = haystack.size();
int len2 = needle.size();
int i = 0,j = 0;
while( (i + j) < len1 && j < len2){
if(haystack[i+j] == needle[j]){
j++;
}else{
i++;
j = 0;
}
}
if(j == len2) return i;
else return -1;
}
};
KMP:耗时6ms(cpp)
class Solution {
public:
int strStr(string haystack, string needle) {
int next[needle.size()];
getNext(needle,next);
int i = 0, j = 0;
int len1 = haystack.size();
int len2 = needle.size();
while(i < len1 && j < len2){
if(haystack[i] == needle[j]){
i++;
j++;
}else{
if(j == 0) i++;
j = next[j];
}
}
if(j == len2) return (i - j);
else return -1;
}
void getNext(string needle,int next[]){
next[0] = 0;
int j = 1,k = 0;
while(j < needle.size()){
if(needle[j] == needle[k]){
next[j] = k;
j++;
k++;
}else if(needle[j] != needle[0]){
next[j] = k;
j++;
k = 0;
}else{
next[j] = k;
j++;
k = 1;
}
}
}
};
BM算法: