File tree Expand file tree Collapse file tree 1 file changed +11
-1
lines changed
String/005.Longest-Palindromic-Substring Expand file tree Collapse file tree 1 file changed +11
-1
lines changed Original file line number Diff line number Diff line change 33### 解法1:
44考虑以每个字符为对称中心(或者为对称中心线左边的字符),同时往左往右推广,看看将回文半径最长能推至哪里。这个解法比较好写,复杂度是o(N^2)
55
6- ### 解法2:
6+ ### 解法2:KMP
77有个更好的线性时间的Manacher算法,可以参考 https://segmentfault.com/a/1190000003914228 这里简单的介绍一下算法。
88
99我们将s = aaaba,填充"#"得到 t = #a#a#a#b#a#,我们令数组P[ i] 表示以t[ i] 为对称中心的最大回文半径(不包括t[ i] 本身)。这样做就是为了解决回文长度奇偶性的问题。在字符串t中,最大的P[ i] 就代表了最长的回文半径。
@@ -25,5 +25,15 @@ X X X {X X X X X X X X X X X} X X X X X
2525这样,我们就可以顺序地探索所有P[ i] ,并找到其中的最大值maxLen,和对应的i的索引maxCenter。注意P的构建是基于t的,那么如何返回基于s的那个回文串呢?其实很巧妙,输出的就是:
2626``` s.substr(maxCenter/2-maxLen/2,maxLen) ```
2727
28+ ### 解法3:Manacher
29+ 本题的本质就是在s中找一个最长的、起点在左端点的回文串。然后将s除去回文串的后端复制、翻转并拼接在原s串的前端,就是最优的答案。
30+
31+ 所以此题的本质就是Manacher的模板题``` 005.Longest-Palindromic-Substring ``` ,求出每个位置作为中心能够构造的最长回文串,查看这个回文串是否能抵达s的最左端,是的话就记录下这个回文串的长度L。输出的答案是:
32+ ``` cpp
33+ string temp = s.substr(R);
34+ reverse (temp.begin(), temp.end());
35+ return temp+s;
36+ ```
37+
2838
2939[Leetcode Link](https://leetcode.com/problems/longest-palindromic-substring)
You can’t perform that action at this time.
0 commit comments