Question SolutionGiven a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

Leetcode:【DP】Longest Palindromic Substring  解题报告
经典的DP题目。

主页君给出3种解法:

1. Brute Force

GitHub代码链接

这个非常Straight Forward,就是开始节点i从0-len-1遍历一次,结束结点以i - Len-1遍历一次。每个字符串都
判断它是不是回文,判断是不是回文也可以使用递归来做。总的复杂度是
Time:O(n^3), Space:O(1)

2. DP

DP 因为是二维动态规划 
Time:O(n^2), Space:O(n^2)

 1 public String longestPalindrome(String s) {
 2         if (s == null) {
 3             return null;
 4         }
 5         
 6         String ret = null;
 7         
 8         int len = s.length();
 9         int max = 0;
10         
11         boolean[][] D = new boolean[len][len];
12         
13         for (int j = 0; j < len; j++) {
14             for (int i = 0; i <= j; i++) {
15                 D[i][j] = s.charAt(i) == s.charAt(j) && (j - i <= 2 || D[i + 1][j - 1]);
16                 if (D[i][j]) {
17                     if (j - i + 1 > max) {
18                         max = j - i + 1;
19                         ret = s.substring(i, j + 1);
20                     }
21                 }
22             }
23         }
24         
25         return ret;
26     }
View Code

相关文章: