/**
* for string c1c2c3c4 ... cn,
* check every substring of the string,
* substrings may start from c1, c2, c3, ... respectively
*/
public class Solution {
public String longestPalindrome(String s) {
int lo = 0, hi = 0, maxLen = 0, currLen = 0;
char[] arr = s.toCharArray();
// check every sub sequency
for (int i=0; i<arr.length; i++) {
if (i > arr.length - maxLen) break;
for (int j=i+1; j<arr.length; j++) {
currLen = j - i + 1;
if (currLen <= maxLen) continue;
if (isPalindrome(i, j, arr)) {
lo = i;
hi = j;
maxLen = currLen;
}
}
}
return s.substring(lo, hi+1);
}
public static boolean isPalindrome(int lo, int hi, char[] arr) {
while (lo < hi) {
if (arr[lo] != arr[hi]) return false;
lo++;
hi--;
}
return true;
}
}
dynamic programming solution
public class Solution {
public String longestPalindrome(String s) {
int len = s.length();
int maxLen = 0, lo = 0, hi = 0;
char[] arr = s.toCharArray();
boolean[][] dp = new boolean[len][len];
// from bot to top dp solution.
// e.g. the length of string is 5 that is 0 1 2 3 4
// 44
// 33 34
// 22 23 24
// 11 12 13 14
// 00 01 02 03 04
// therefore, if 23 is a palindrome then if arr[1] == arr[4]
// then we know 14 is also a palindrome.
// we can deduce every dp[i][j] from the previous results.
for (int i=len-1; i>=0; i--)
for (int j=i; j<len; j++) {
dp[i][j] = (arr[i] == arr[j]) && (j-i<3 || dp[i+1][j-1]);
if (j-i+1 > maxLen && dp[i][j]) {
lo = i;
hi = j;
maxLen = j - i + 1;
}
}
return s.substring(lo, hi+1);
}
}