BF算法,即暴風(Brute Force)算法,是普通的模式匹配算法,BF算法的思想就是將目標串S的第一個字符與模式串T的第一個字符進行匹配,若相等,則繼續比較S的第二個字符和 T的第二個字符;若不相等,則比較S的第二個字符和T的第一個字符,依次比較下去,直到得出最後的匹配結果。BF算法是一種蠻力算法。
該算法最壞情況下要進行M*(N-M+1)次比較,時間複雜度爲O(M*N)。
KMP算法要解決的問題就是在字符串(也叫主串)中的模式(pattern)定位問題。說簡單點就是我們平時常說的關鍵字搜索。模式串就是關鍵字(接下來稱它爲P),如果它在一個主串(接下來稱爲T)中出現,就返回它的具體位置,否則返回-1(常用手段)。
KMP算法是一種改進的字符串匹配算法,由D.E.Knuth,J.H.Morris和V.R.Pratt同時發現,簡稱KMP算法,KMP算法的關鍵是利用匹配失敗後的信息,儘量減少模式串與主串的匹配次數以達到快速匹配的目的。具體實現就是實現一個next()函數,函數本身包含了模式串的局部匹配信息。
時間複雜度O(m+n)。
BF實現:
//查找子串
int BF(PString ps, PString pp)
{
if (ps == NULL || pp == NULL)
{
return -1;
}
int i = 0;
int j = 0;
while (i < ps->curlen && j < pp->curlen)
{
if (ps->pstr[i] == pp->pstr[j])
{
i++;
j++;
}
else
{
i = i - j + 1;
j = 0;
}
}
if (j >= pp->curlen)
{
return i - j;
}
return -1;
}
KMP算法:
void GetNext(PString ps, int* next)
{
if (ps == NULL)
{
return;
}
int k = -1;
int i = 1;
int len = ps->curlen;
if (len == 0)
{
return;
}
next[0] = -1;
if (len == 1)
{
return;
}
next[1] = ++k;
while (i < len - 1)
{
if (k == -1 || ps->pstr[i] == ps->pstr[k])
{
//next[i + 1] = k + 1;
//i++;
//k++;
next[++i] = ++k;
}
else
{
k = next[k];
}
}
}
int KMP(PString ps1, PString ps2)
{
if (ps1 == NULL || ps2 == NULL)
{
return -1;
}
int len1 = ps1->curlen;
int len2 = ps2->curlen;
int i = 0;
int j = 0;
int* next = (int*)malloc(sizeof(int)*len2);
GetNext(ps2, next);
while (i < len1 && j < len2)
{
if (j == -1 || ps1->pstr[i] == ps2->pstr[j])
{
++i;
++j;
}
else
{
j = next[j];
}
}
free(next);
if (j >= len2)
{
return i - j;
}
return -1;
}