categories: leetcode


5.png

题目描述

Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1: Input: “babad” Output: “bab” Note: “aba” is also a valid answer.Example 2: Input: “cbbd” Output: “bb”

参考代码

  1. class Solution {
  2. public String longestPalindrome(String s) {
  3. if (s == null || s.length() < 1) return "";
  4. int start = 0, end = 0;
  5. for (int i = 0; i < s.length(); i++) {
  6. int len1 = expandAroundCenter(s, i, i);//奇数
  7. int len2 = expandAroundCenter(s, i, i + 1);//偶数
  8. int len = Math.max(len1, len2);
  9. if (len > end - start) {
  10. start = i - (len - 1) / 2;//确使奇偶行得通
  11. end = i + len / 2;
  12. }
  13. }
  14. return s.substring(start, end + 1);
  15. }
  16. private int expandAroundCenter(String s, int left, int right) {
  17. int L = left, R = right;
  18. while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R))
  19. {
  20. L--;
  21. R++;
  22. }
  23. return R - L - 1;//因为循环结束时,长度各边减一
  24. }
  25. }

思路及总结

偶数减一除以二(0.5-1.0)和奇数减一除以二(0.0-0.5)两者可以保持除法上的一致。
官方首先提醒了最长公共子串的误区,然后列举了暴力法,动态规划,和本题的中心扩展法。详细内容直接参考官方题解。

参考

https://leetcode-cn.com/problems/longest-palindromic-substring/solution/
https://leetcode.com/problems/longest-palindromic-substring/solution/
Manacher 算法
https://segmentfault.com/a/1190000008484167