字符串查找(2) KMP算法查找目标字符串
先上代码:
class KMP
{
using DFA_t = vector< vector<int> >;
public:
KMP(const string &needle)
: m_NeedleSize{ (int)needle.size() },
m_DFA(TOTAL_CHAR, std::move(vector<int>(m_NeedleSize, 0)))
{
if (m_NeedleSize > 0)
{
m_DFA[(unsigned char)needle[0]][0] = 1;
}
// generate dfa table by needle str
for (int i = 1, j = 0; i < m_NeedleSize; i++)
{
unsigned char cur = needle[i];
for (int k = 0; k < TOTAL_CHAR; k++)
{
m_DFA[k][i] = m_DFA[k][j];
}
m_DFA[cur][i] = i + 1;
j = m_DFA[cur][j];
}
// PrintDFA(m_DFA);
}
int SearchIn(const string &haystack) const
{
if (m_NeedleSize == 0) return 0;
const int haystackSize { (int)haystack.size() };
for (int i = 0, j = 0; i < haystackSize; i++)
{
j = m_DFA[(unsigned char)haystack[i]][j];
if (j == m_NeedleSize)
{
return i - j + 1;
}
}
return -1;
}
private:
static const int TOTAL_CHAR;
int m_NeedleSize;
DFA_t m_DFA;
};
const int KMP::TOTAL_CHAR = 256;
leetcode上测试相比暴力字符串查找方法速度快了近10倍
每个字母匹配分三种情况:
- 匹配到对应字符,模式指针j指向下一个位置.即j+=1;
- 没有匹配到对应字符,但是匹配到公共字符前缀.这种情况下,根据在公共字符前缀中的位置决定模式指针指向的位置
- 没有匹配到公共字符前缀,这种情况下直接移动模式指针j到模式字符串开头,重新开始匹配
根据上述构建DFA的函数KMP::KMP()可知构造时间复杂度为O(KMP::TOTAL_CHAR * M),空间复杂度为O(KMP::TOTAL_CHAR * M)
M表示模式匹配字符串的长度
KMP算法的优点是对于相同的模式字符串,只需要构造一次DFA矩阵
缺点是比较大的空间复杂度
查找函数KMP::SearchIn时间复杂度为O(N),空间复杂度为O(1)。
综合看来完全匹配一次时间复杂度为O(KMP::TOTAL_CHAR * M + N),空间复杂度为O(KMP::TOTAL_CHAR * M)
浙公网安备 33010602011771号