KMP算法学习&总结
1、传统的字符串匹配算法
/*
* 从s中第sIndex位置开始匹配p
* 若匹配成功,返回s中模式串p的起始index
* 若匹配失败,返回-1
*/
int index(const std::string &s, const std::string &p, const int sIndex = 0)
{
int i = sIndex, j = 0;
if (s.length() < 1 || p.length() < 1 || sIndex < 0)
{
return -1;
}
while (i != s.length() && j != p.length())
{
if (s[i] == p[j])
{
++i;
++j;
}
else
{
i = i - j + 1;
j = 0;
}
}
return j == p.length() ? i - j: -1;