zoukankan      html  css  js  c++  java
  • Manacher 算法(最长回文子串)

     1 #include <bits/stdc++.h>
     2 
     3 using namespace std;
     4 
     5 char s[10000]; // 原字符串
     6 char ss[10000]; // 新构造的字符串
     7 int r[10000]; // 回文半径
     8 
     9 int manachar() {
    10     int loop = 1, len = strlen(s), ans = 0;
    11     int max_right = 0, max_mid = 0; // 最大右边界和回文中心
    12     //构建新字符串
    13     ss[0] = '$';
    14     for(int j = 0; j < len; j++) {
    15         ss[loop++] = '|';
    16         ss[loop++] = s[j];
    17     }
    18     ss[loop++] = '|';
    19     ss[loop++] = '#';
    20     
    21     len = loop;
    22     for(int i = 1; i < len; i++) {
    23         if(i < max_right) // 根据回文的性质进行的操作
    24             r[i]  = min(r[2*max_mid-i], max_right-i); // 2*max_mid-i表示i对于中心点的对称点,max_right-i表示边界到i的距离
    25         else
    26             r[i] = 1; //从1开始
    27         while(ss[i+r[i]] == ss[i-r[i]]) // 更新最大半径
    28             r[i]++;
    29         if(i + r[i] > max_right) { // 更新最大右边界
    30             max_right = i + r[i];
    31             max_mid = i;
    32         }
    33         if(r[i] - 1 > ans) // 更新结果
    34             ans = r[i] - 1;
    35     }
    36     return ans;
    37 }
    38 int main() {
    39     int max_lenth;
    40     scanf("%s", s);
    41     max_lenth = manachar();
    42     printf("%d
    ", max_lenth);
    43     return 0;
    44 }
  • 相关阅读:
    剑指offer二十九---最小的k个数
    Select2插件 点击、选中事件 解读
    Datatable插件的简单的使用方式 和 学习方式
    java map获取值方式
    mysql delete语句使用别名报错
    springmvc 添加@ResponseBody
    maven 创建后报错
    nodejs
    gulp
    Nodejs-express 4.0框架 简单介绍
  • 原文地址:https://www.cnblogs.com/knightoflake/p/13799299.html
Copyright © 2011-2022 走看看