kmp,E-kmp,manacher,ac自动机
KMP
http://t.cn/EZlzRyg
Manacher—最长回文串O(N)
关于求最长回文串办法
四种方法求最长回文串
但是上面几种都不是最快的,最快的是Manacher(马拉车)算法,算法复杂度是O(N)
Manacher
https://www.cnblogs.com/grandyang/p/4475985.html
https://www.cnblogs.com/z360/p/6375514.html
https://segmentfault.com/a/1190000008484167
https://www.bilibili.com/video/av4829276?from=search&seid=9253656566579281943
https://www.bilibili.com/video/av20495920?from=search&seid=9253656566579281943
注意,此题别的算法O(NlogN)都会超时,所以只能用马拉车的O(N)算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
#include <iostream> #include <algorithm> #include <string> using namespace std; const int MAXN = 1E6; int p[MAXN]; string Manacher(string s) { string t = "$#"; for (int i = 0; i < s.size(); i++) { t += s[i]; t += "#"; } int mx = 0, id = 0, maxLen = 0, maxCenter = 0; for (int i = 1; i < t.size(); ++i) { p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1; while (t[i + p[i]] == t[i - p[i]]) ++p[i];
if (mx < i + p[i]) { mx = i + p[i]; id = i; } if (maxLen < p[i]) { maxLen = p[i]; maxCenter = i; } } return s.substr((maxCenter - maxLen) / 2, maxLen - 1); } int main() { ios::sync_with_stdio(false); string s; while(cin >> s) { cout << Manacher(s).size() << endl; } return 0; }
|