最长回文子串 V2(Manacher算法)

来源:互联网 发布:淘宝休闲斜挎包 编辑:程序博客网 时间:2024/06/01 18:45
回文串是指aba、abba、cccbccc、aaaa这种左右对称的字符串。
输入一个字符串Str,输出Str里最长回文子串的长度。
Input
输入Str(Str的长度 <= 100000)
Output
输出最长回文子串的长度L。
Input示例
daabaac
Output示例
5

#include <iostream>#include <vector>#include <algorithm>#include <string.h>using namespace std;int fun(string &str){string temp;int len = str.length();temp += '@';for (int i = 0; i < len; i++){temp += '#';temp += str[i];}temp += '#';temp += '&';int size = len*2 + 1;int pos = 0;int right = 0;int result = 0;int buf[size];for (int i = 1; i < size; i++){if (i < right){buf[i] = min(buf[2*pos-i], right-i);}else{buf[i] = 1;}while (temp[i-buf[i]] == temp[i+buf[i]]){buf[i]++;}if (i+buf[i] > right){pos = i;right = i+buf[i];}result = max(result, buf[i]);}return result-1;}int main(){string str;cin >> str;cout << fun(str) << endl;    return 0;}


原创粉丝点击