题解 | #最长回文子串#
最长回文子串
http://www.nowcoder.com/practice/b4525d1d84934cf280439aeecc36f4af
import java.util.*; public class Solution { public int getLongestPalindrome(String A, int n) { // write code here boolean[][] dp = new boolean[n][n]; int max = 1; for(int i = 0; i < n; i++){ dp[i][i] = true; if(i<A.length()-1){ if(A.charAt(i)==A.charAt(i+1)){ dp[i][i+1] = true; max = 2; } } } for(int L = 3; L <= n; L++){//枚举字符串长度 for(int i = 0; i+L-1 <n;i++){//枚举字串起始点,起始点加上字串长度必须小于A的长度,也就是最大小标小于A的长度 int j = i+L-1;//子串右端点 if(A.charAt(i) == A.charAt(j)&&dp[i+1][j-1]){ dp[i][j] = true; max = L;//更新字符串长度 } } } return max; } }