Horspool算法
假设模式为p[0,…,m-1] 文本为T[0,…,n-1]
问题的关键是每次遇到不匹配的字符,移动的元素个数
假设对齐时,文本对应于模式的最后一个的字符为c
那么每次移动的距离为
模式的长度m(如果模式中没有c)
t(c) =
前m-1个字符中c到最右边字符的距离
这样我们可以先初始化一个table[256]都初始为模式的长度m
for i 0->m-2 //前m-1个字符
table[P[i]]=m-1-i;
这样每次就可以根据不相同的元素直接找到移动的距离
eg
对于模式BARBER,
i=0 table[B] = 6-1-0=5;
i=1 table[A] = 6-1-1=4;
i=2 table[R] = 6-1-2=3;
i=3 table[B] = 6-1-3=2;
i=4 table[E] = 6-1-4=1;
这样 除了EBRA的移动长度分别为1234外,其余都为m即6
代码
class Solution {
public:
int strStr(string haystack, string needle) {
string::size_type sz_n=needle.size();
string::size_type sz_h=haystack.size();
if(needle==string()) return 0;
//if(haystack==string()) return -1;
vector<int> table(256,sz_n); //记录每次移动的距离
for(int i = 0; i<sz_n-1;++i)
table[needle[i]]=sz_n-1-i;
int idx = sz_n-1; //haystack中开始匹配的位置,从右往左匹配,初始为needle最右边的字符
while(idx<sz_h){
int match = 0; //匹配的字符数
while(match<sz_n&&needle[sz_n-1-match]==haystack[idx-match])
match++;
if(match == sz_n) //匹配了needle
return idx-match+1;
else
idx+=table[haystack[idx]];
}
return -1;
}
};
平均效率O(n)
在移动的过程中
HorspoolMatching(P[0,...,m-1],T[0,...,n-1])
//输入:模式P[0,...,m-1],文本T[0,...,n-1]
//输出:第一个匹配字串最左端字的下标,但如果没有匹配字串,输出-1 shiftTable(P[0,..m-1])
i<——m-1 //文本中模式最右端的位置
while i<n do
k<-0 //匹配的字符数
while(k<m&&P[m-1-k]==T[i-k])
++k;
if k==m
return i-k+1;
else
**i += table[P[i]];** return -1;
一个没有那么高效但是很简洁的代码
int strStr(char *haystack, char *needle) {
if (!haystack || !needle) return -1;
for (int i = 0; ; ++i) {
for (int j = 0; ; ++j) {
if (needle[j] == 0) return i;
if (haystack[i + j] == 0) return -1;
if (haystack[i + j] != needle[j]) break;
}
}
}