KMP algorithm for string matching。 以下是我在網上找到了計算的最長前綴後綴數組code:
認定中:字符串匹配:使用kmp算法計算最長的前綴後綴數組
lps[i] = the longest proper prefix of pat[0..i]
which is also a suffix of pat[0..i].
代碼:
void computeLPSArray(char *pat, int M, int *lps)
{
int len = 0; // length of the previous longest prefix suffix
int i;
lps[0] = 0; // lps[0] is always 0
i = 1;
// the loop calculates lps[i] for i = 1 to M-1
while(i < M)
{
if(pat[i] == pat[len])
{
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
if(len != 0)
{
// This is tricky. Consider the example AAACAAAA and i = 7.
len = lps[len-1]; //*****************
// Also, note that we do not increment i here
}
else // if (len == 0)
{
lps[i] = 0;
i++;
}
}
}
}
我可以用len = len-1
代替len = lps[len-1]
?
因爲len始終像從[0 .. someIndex]那樣計算前綴長度。那麼爲什麼要在這裏使用lps進行分配?以下是我測試了其正常工作的情況下(第一行是圖案和隨後的兩行是原始和改進分配的結果len
):
a a a b a b c
0 1 2 0 1 0 0
0 1 2 0 1 0 0
a b c b a b c
0 0 0 0 1 2 3
0 0 0 0 1 2 3
a a b c b a b
0 1 0 0 0 1 0
0 1 0 0 0 1 0
代碼在這裏有兩個變化寫着:http://ideone.com/qiSrUo