5. 最长回文子串 Posted on 2018-09-10 | In leetcode Words count in article: 249 | Reading time ≈ 1 题目给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。 示例1123输入: "babad"输出: "bab"注意: "aba" 也是一个有效答案。 示例2:12输入: "cbbd"输出: "bb" 解法解法一:Java12345678910111213141516171819202122232425262728293031323334353637383940414243class Solution {public: string longestPalindrome(string s) { const int len = s.size(); if(len <= 1)return s; string str = preProcess(s); int n = str.size(), id = 0, mx = 0; vector<int>p(n, 0); for(int i = 1; i < n-1; i++) { p[i] = mx > i ? min(p[2*id-i], mx-i) : 1; while(str[i+p[i]] == str[i-p[i]])p[i]++; if(i + p[i] > mx) { mx = i + p[i]; id = i; } } int maxLen = 0, index = 0; for(int i = 1; i < n-1; i++) if(p[i] > maxLen) { maxLen = p[i]; index = i; } return s.substr((index - maxLen)/2, maxLen-1); } string preProcess(const string &s) { int n = s.size(); string res; res.push_back('$'); res.push_back('#'); for(int i = 0; i < n; i++) { res.push_back(s[i]); res.push_back('#'); } res.push_back('^'); return res; }};