[LeetCode]KMP——字符串匹配
class Solution {
public:
/*//暴力法
int strStr(string haystack, string needle) {
int i = 0,j = 0;
if(needle.empty())
return 0;
while(i<haystack.size()&&j<needle.size())
{
if(haystack[i] == needle[j])
{
i++;
j++;
}
else
{
i = i-j+1;
j = 0;
}
if(j == (needle.size()))
return i-j;
}
return -1;
}
*/
vector<int> cal_next(string p)
{
vector<int> next(p.size(),0);
next[0] = -1;
int j = 0, k = -1;
while (j < p.size() - 1) {
if (k == -1 || p[j] == p[k]) {
if(p[j+1] == p[k+1])
next[++j] == next[++k];
else
next[++j] = ++k;
}
else {
k = next[k];
}
}
return next;
}
int strStr(string haystack, string needle) {
if (needle.empty())return 0;
vector<int> next = cal_next(needle);
int i = 0, j = 0;
while(i<haystack.size() && j<(int)needle.size())//一个大坑,不加(int)的话,size()为无符号类型,当j==-1时将会被转化为INT_MAX!
{
if (j == -1 || haystack[i] == needle[j])// 当j为-1时,要移动的是i,当然j也要归0
{
i++;
j++;
}
else
{
j = next[j];
}
}
if (j == needle.size())
return i - j;
else
return -1;
}
};