Longest Palindromic Substring

Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.

 

 1 public class Solution {
 2     public String longestPalindrome(String s) {
 3         if(s.length()<=1) return s;
 4         int len = s.length();
 5         boolean dp[][] = new boolean[len][len];
 6         int max = 0;
 7         int start = 0;
 8         int end = 0;
 9         for(int i=len-1;i>=0;i--){
10             for(int j=i;j<len;j++){
11                 if(s.charAt(i)==s.charAt(j) &&(j-i<2||dp[i+1][j-1])){
12                     dp[i][j]=true;
13                     if(j-i+1>max){
14                         max = j-i+1;
15                         start = i;
16                         end = j;
17                     }
18                 }
19             }
20         }
21         return s.substring(start,end+1);
22     }
23 }
View Code

 

posted @ 2014-02-06 04:55  krunning  阅读(102)  评论(0编辑  收藏  举报