KMP算法C++代码的实现。
#include <iostream>
#include <string>
#include <windows.h>
#include <vector>
using namespace std;
//朴素法找字串
int Index(string S, string T)
{
int i = 0, j = 0;
while (i <S.length() && j < T.length())
{
if (S[i] == T[i])
{
i++; j++;
}
else
{
i = i - j + 2;
j = 1;
}
}
if (j > T.length())
return i - T.length();
else
return 0;
}
//求模式串T的next数组
void get_next(string T, vector<int>& next)
{
if (T.length() == 1)
{
next.push_back(-1);
}
next.resize(T.length());
next[0] = -1;
next[1] = 0;
int i = 2; //i 为要求子字符串字符next数组的下标
int cn = 0;//cn等于跳转
while (i < next.size())
{
if (T[i - 1] == T[cn])//这个字符的前一个字符 和 跳转的字符(cn-1)的后一个字符即为cn.
{
/*cn++;
next[i] =cn;
i++*/
next[i++] = ++cn;
}
else if (cn > 0)//我还可以往前跳
{
cn = next[cn];
}
else//已经在0位置 跳不过去了
{
next[i] = 0;
i++;
}
}
}
//KMP算法 S是主串,T是子串
int Index_KMP(string S, string T)
{
if (S == "" || T == "" || S.length() < 1 || S.length() < T.length())
{
return -1;
}
int i = 0, j = 0;
vector<int> next;
get_next(T, next);
while (i < S.length() && j < T.length())
{
if (S[i] == T[j])
{
++i;
++j;
}
else if (next[j] == -1)
{
i++;
}
else
{
j = next[j];
}
}
return j == T.length() ? i - j : -1;
}
int main()
{
string a = "abcdefg";
string b = "cde";
cout << Index_KMP(a, b);
}