zoukankan      html  css  js  c++  java
  • [leetcode]Longest Palindromic Substring

    题目链接:https://leetcode.com/problems/longest-palindromic-substring/

    输出最长的回文串

     1 class Solution {
     2 public:
     3     int pre[22222];
     4     char x[22222];
     5     char str[22222];
     6 
     7     int min(int x, int y) {
     8         return x < y ? x : y;
     9     }
    10 
    11     int init(char *str, char *x) {
    12         int len = strlen(x);
    13         str[0] = '$';
    14         for (int i = 0; i <= len; i++) {
    15             str[2 * i + 1] = '#';
    16             str[2 * i + 2] = x[i];
    17         }
    18         len = 2 * len + 2;
    19         str[len] = 0;
    20         return len;
    21     }
    22     void manacher(int *pre, char *str, int len) {
    23         int id = 0;
    24         int mx = 0;
    25         for (int i = 1; i < len; i++) {
    26             pre[i] = mx > i ? min(pre[2 * id - i], mx - i) : 1;
    27             while (str[i + pre[i]] == str[i - pre[i]])   pre[i]++;
    28             if (pre[i] + i > mx) {
    29                 id = i;
    30                 mx = pre[id] + id;
    31             }
    32         }
    33     }
    34     string longestPalindrome(string s) {
    35         memset(pre, 0, sizeof(pre));
    36         memset(str, 0, sizeof(str));
    37         int len = init(str, const_cast<char*>(s.data()));
    38         manacher(pre, str, len);
    39         int fuck = 1, pos = 0;
    40         for (int i = 0; i < len; i++) {
    41             if (fuck < pre[i]) {
    42                 fuck = pre[i];
    43                 pos = i;
    44             }
    45         }
    46         pos--;
    47         fuck--;
    48         string ans;
    49         for (int i = pos - fuck + 1; i <= pos + fuck + 1; i++) {
    50             if (i % 2 == 0) {
    51                 ans.push_back(str[i]);
    52             }
    53         }
    54         return ans;
    55     }
    56 };
  • 相关阅读:
    ACdream群赛(4) B Double Kings
    ACdream群赛(4)总结
    250E Mad Joe
    ZOJ Monthly, November 2012 I Search in the Wiki
    251C Number Transformation
    253D Table with Letters 2
    Codeforces Round #153 (Div. 2) 总结
    ACdream群赛(4) D Draw a Mess
    ZOJ Monthly, November 2012 G Gao The Sequence
    在vs2005/c++中捕获浮点数异常
  • 原文地址:https://www.cnblogs.com/kirai/p/4925772.html
Copyright © 2011-2022 走看看