Method 2 ( Dynamic Programming )
The time complexity can be reduced by storing results of subproblems. The idea is similar to this post. We maintain a boolean table[n][n] that is filled in bottom up manner. The value of table[i][j] is true, if the substring is palindrome, otherwise false. To calculate table[i][j], we first check the value of table[i+1][j-1], if the value is true and str[i] is same as str[j], then we make table[i][j] true. Otherwise, the value of table[i][j] is made false.
// 5. Longest Palindromic Substring
// Dynamic Programming
// Time complexity: O ( n^2 )
// Auxiliary Space: O ( n^2 )
class Solution {
public String longestPalindrome(String s) {
if (s == null || s.length() <= 1) {
return s;
}
boolean[][] isPalindrome = new boolean[s.length()][s.length()];
int maxLen = 1;
String longest = s.substring(0, 1);
for (int len = 0; len < s.length(); len++) {
for (int i = 0; i < s.length() - len; i++) {
int j = i + len;
if (s.charAt(i) == s.charAt(j) && (len <= 2 || isPalindrome[i+1][j-1])) {
isPalindrome[i][j] = true;
if (len + 1 > maxLen) {
maxLen = len + 1;
longest = s.substring(i, j+1);
}
}
}
}
return longest;
}
}