#include <iostream>
#include <string>
int next[255];
void getnext(const std::string &str)
{
int i = 0;
int j = -1;
next[0] = -1;
while (i < str.size())
{
if (j == -1 || str[i] == str[j])
{
++i;
++j;
if (str[i] == str[j])
{
next[i] = next[j];
}
else
{
next[i] = j;
}
}
else
{
j = next[j];
}
}
}
int IndexKMP(const std::string &str, const std::string& test_str)
{
getnext(test_str);
int index = -1;
int i = 0;
int j = 0;
while (i < (int)str.size() && j < (int)test_str.size())
{
if (j == -1 || str[i] == test_str[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
if (j >= (int)test_str.size())
{
index = i - test_str.size();
}
return index;
}
int main()
{
std::string str("abcdabdcabaaabaace");
std::string test("abaac");
int index = IndexKMP(str, test);
std::cout << index << std::endl;
return 0;
}
有符号数与无符号数比较的坑:
有符号与无符号比较:有符号数会转换成无符号数来进行比较(如int 与 unsigned int 比较,int 转换成 unsigned int)。
有符号与非无符号数比较:非无符号转化成有符号(如int 与 unsigned char比较,unsigned char 转换成 int)。
无符号与非有符号数比较:非有符号转化成有符号(如unsigned int 与 char比较,char 转换成 unsigned int)。