kmp中文匹配算法
闲来无事写了一个c++的kmp算法,希望大家给出批评和建议。
#pragma once
#ifndef KMP_H
#define KMP_H
#include
#include
#include
using namespace std;
vector getStringArray(string& s)
{
vector sa;
for (int i = 0; i < s.size(); i++)
{
if (s[i] & 0x80)
{
sa.push_back(s.substr(i, 2));
i++;
}
else
{
sa.push_back(s.substr(i, 1));
}
}
return sa;
}
vector getNextArray(vector& s)
{
vector ia;
if (s.size() == 0)
return ia;
ia.push_back(0);
if (s.size() == 1)
return ia;
int i = 0, j = 1;
while (i <= s.size() - 1 && j <= s.size() - 1)
{
if (s[i] == s[j])
{
ia.push_back(i + 1);
i++;
j++;
}
else
{
if (i == 0)
{
ia.push_back(0);
j++;
}
else
{
while (i > 0 && s[i] != s[j])
{
i = ia[i - 1];
}
if (s[i] == s[j])
{
ia.push_back(i + 1);
i++;
j++;
}
else
{
ia.push_back(0);
j++;
}
}
}
}
return ia;
}
int KMP(string str1, string str2)
{
vector s1 = getStringArray(str1);
vector s2 = getStringArray(str2);
vector next = getNextArray(s2);
int j = 0;
for (int i = 0; i < s1.size(); i++)
{
while (j > 0 && s1[i] != s2[j])
{
j = next[j - 1];
}
if (s1[i] == s2[j])
j++;
if (j == s2.size())
return i - s2.size() + 1;
}
return -1;
}
#endif // !KMP_H