public static String longestPalindrome(String s) { if(null==s||s.length()==0) return s; int n=s.length(); char[]c=s.toCharArray(); int[][]dp=new int[n][n]; int max=0,imax=0,jmax=0; for(int i=0;i<n;i++){ dp[i][i]=1; if(i+1<n&&c[i]==c[i+1]){ dp[i][i+1]=2; if(dp[i][i+1]>max) { max=dp[i][i+1]; imax=i; jmax=i+1; } } } for(int i=0;i<n;i++){ for(int j=1;i+j<n&&i-j>=0;j++){ if(i+1<n&&c[i+j]==c[i-j]){ dp[i-j][i+j]=dp[i-j+1][i+j-1]+2; if(dp[i-j][i+j]>max) { max=dp[i-j][i+j]; imax=i-j; jmax=i+j; } }else break; } } for(int i=0;i<n;i++){ for(int j=1;i+j<n&&i-j>=0;j++){ if(i+1<n&&i-j>=0&&i+1+j<n&&dp[i][i+1]!=0&&c[i-j]==c[i+1+j]){ dp[i-j][i+1+j]=dp[i-j+1][i+j]+2; if(dp[i-j][i+j+1]>max) { max=dp[i-j][i+j+1]; imax=i-j; jmax=i+j+1; } }else break; } } return s.substring(imax,jmax+1); }