REF: http://fisherlei.blogspot.com/2012/12/leetcode-longest-palindromic-substring.html
DP solution
定义函数P[i,j] = 字符串区间[i,j]是否为palindrome.
首先找个例子,比如S="abccb",
S= a b c c b
Index = 0 1 2 3 4
P[0,0] =1 //each char is a palindrome
P[0,1] =S[0] == S[1] , P[1,1] =1
P[0,2] = S[0] == S[2] && P[1,1], P[1,2] = S[1] == S[2] , P[2,2] = 1
P[0,3] = S[0] == S[3] && P[1,2], P[1,3] = S[1] == S[3] && P[2,2] , P[2,3] =S[2] ==S[3], P[3,3]=1
......................
由此就可以推导出规律
P[i,j] = 1 if i ==j
= S[i] ==S[j] if j = i+1
= S[i] == S[j] && P[i+1][j-1] if j>i+1
代码如下所示:
<div>
</div>public class Solution { public String longestPalindrome(String s) { if (s == null) { return null; } int len = s.length(); if (len == 0) { return ""; } int max = 0; int rets = 0; // record the solution start int rete = 0; // record the solution end // ref: http://fisherlei.blogspot.com/2012/12/leetcode-longest-palindromic-substring.html boolean isP[][] = new boolean[len][len]; for (int end = 0; end < len; end++) { for (int start = 0; start <= end; start++) { if (start == end) { isP[start][end] = true; } else { // 1: start == end - 1, true if s.charAt[start] == s.charAt[end] // 2: start < end - 1, true if s.charAt[start] == s.charAt[end] && isP[start + 1][end - 1]) isP[start][end] = s.charAt(start) == s.charAt(end) && (start == end - 1 || isP[start + 1][end - 1]); } if (isP[start][end] && max < end - start + 1) { max = end - start + 1; rets = start; rete = end; } } } return s.substring(rets, rete + 1); } }