码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode]Longest Palindromic Substring

时间:2015-10-31 17:14:56      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

题目链接: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 };

 

[leetcode]Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/vincentX/p/4925772.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!