生活随笔
收集整理的這篇文章主要介紹了
扩展kmp
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
擴展kmp可以解決什么問題?
- 擴展kmpkmpkmp可以O(N+M)O(N+M)O(N+M)解決SSS的所有后綴與TTT的最長公共前綴
S[i]S[i]S[i]:SSS的后綴Si....nS_{i....n}Si....n?
ex[i]ex[i]ex[i]:lcp(S[i],T)lcp(S[i], T)lcp(S[i],T)
nex[i]nex[i]nex[i]:串自己的exexex,nex[i]nex[i]nex[i]的后綴和它本身的最長公共前綴 - 如果ex[i]=lenTex[i] = len_{T}ex[i]=lenT?表示TTT在S[i]S[i]S[i]中出現,可以用來模式匹配
struct exKMP
{int nex
[maxn
], ex
[maxn
]; void get_nex(char *str
, int len
) {int i
= 0, j
, pos
;nex
[0] = len
;while (str
[i
] == str
[i
+1] && i
+1 < len
) ++i
;nex
[1] = i
;pos
= 1;for (int i
= 2; i
< len
; ++i
) {if (nex
[i
-pos
] + i
< nex
[pos
] + pos
) nex
[i
] = nex
[i
-pos
];else {j
= nex
[pos
] + pos
- i
;if (j
< 0) j
= 0;while (i
+j
< len
&& str
[j
] == str
[j
+i
]) ++j
;nex
[i
] = j
;pos
= i
;}}}void get_ex(char *s1
, char *s2
) { int i
= 0, j
, pos
;int len1
= strlen(s1
);int len2
= strlen(s2
);get_nex(s2
, len2
);while (s1
[i
] == s2
[i
] && i
< len1
&& i
< len2
) ++i
;ex
[0] = i
;pos
= 0;for (int i
= 1; i
< len1
; ++i
) {if (nex
[i
-pos
] + i
< ex
[pos
] + pos
) ex
[i
] = nex
[i
-pos
];else {j
= ex
[pos
] + pos
- i
;if (j
< 0) j
= 0;while (i
+j
< len1
&& j
< len2
&& s1
[i
+j
] == s2
[j
]) ++j
;ex
[i
] = j
;pos
= i
;}}}
}ek
;
與50位技術專家面對面20年技術見證,附贈技術全景圖
總結
以上是生活随笔為你收集整理的扩展kmp的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。