一、相关题目

https://leetcode.com/problems/longest-palindromic-substring/

二、解题思路

1、朴素暴力法(不可取)

扫描所有的字串,记录最长的,复杂度为11+22+33+…+nn,即O(n)。

2、动态规划

P(i, j) 代表从i到j的字串是否为回文串
P(i, i)=true, P(i, i + 1)=(S== S)
P(i, j) = P(i + 1, j - 1) && (S== S)

3、最长相似串

三、总结

方法 时间复杂度 空间复杂度 备注
暴力求解 O(n) O(1) 不推荐
动态规划 O(n) O(n)
最长相似串
中心扩张
Manacher’s Algorithm O(n) O(n) https://www.hackerrank.com/topics/manachers-algorithm

附录

动态规划代码

  1. public String longestPalindrome(String s) {
  2. if(s == null || s.isEmpty()) {
  3. return "";
  4. }
  5. int len = s.length();
  6. String result = s.substring(0, 1);
  7. boolean[][] dp = new boolean[len][len];
  8. for (int i = 0; i < len; i++) {
  9. dp[i][i] = true;
  10. }
  11. for (int i = 0; i < len - 1; i++) {
  12. if (s.charAt(i) == s.charAt(i + 1)) {
  13. dp[i][i + 1] = true;
  14. result = s.substring(i, i + 2);
  15. }
  16. }
  17. // loop for length
  18. for (int l = 3; l <= len; l++) {
  19. int lastIdx = len - l;
  20. for (int i = 0; i <= lastIdx; i++) {
  21. int j = i + l - 1;
  22. if (dp[i + 1][j - 1] && s.charAt(i) == s.charAt(j)) {
  23. dp[i][j] = true;
  24. if (l > result.length()) {
  25. result = s.substring(i, j + 1);
  26. }
  27. }
  28. }
  29. }
  30. return result;
  31. }