题目链接:https://leetcode.com/problems/longest-palindromic-substring/
题目:
Given 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.
解析:
两种动态规划:(1)dp[i][j],按照i-j的差值来构造。即外循环为差值diff,从1到length-1。里面便是左边缘的循环,即dp[i][i+diff]
(2)外循环为子串的左边缘位置,内循环为右边缘位置;
上面的递推关系都是一样的,dp[i][j] = dp[i+1][j-1] (s[i] == s[j])
第一种我用的c 语言实现的,下面为第二种的java实现代码:
public class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0) return "";
boolean[][] isPali = new boolean[s.length()][s.length()];
String res = "";
int maxLen = 0;
for (int i = s.length()-1; i >= 0; i--){
for (int j = i; j < s.length(); j++){
if (s.charAt(i) == s.charAt(j) && (j-i <= 2 || isPali[i+1][j-1])){
isPali[i][j] = true;
if (maxLen < j-i+1){
maxLen = j-i+1;
res = s.substring(i, j+1);
}
}
}
}
return res;
}
}