Leetcode-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.

Analysis:

We define the state d[i][j] as whether S[j-i+1...j] is palindromic, i.e., i is length, j the end of the substring.

d[i][j] is true, only when the char S[j-i+1]==S[j] and S[j-i+1...j-1] is palindromic, i.e., d[i-2][j-1] is true.

NOTE: the function substring() is time consuming.

Solution:

 1 public class Solution {
 2     public String longestPalindrome(String s) {
 3         if (s.length()==0 || s.length()==1) return s;
 4         String res = "";
 5         boolean[][] valid = new boolean[s.length()+1][s.length()];
 6         Arrays.fill(valid[0],true);
 7         Arrays.fill(valid[1],true);
 8         int start = 0, end = 0;
 9         for (int i=2;i<=s.length();i++)
10             for (int j=i-1;j<s.length();j++)
11                 if (valid[i-2][j-1] && s.charAt(j-i+1)==s.charAt(j)){
12                     valid[i][j]=true;
13                     //res = s.substring(j-i+1,j+1);
14                     start = j-i+1;
15                     end = j+1;
16                 } else valid[i][j]=false;
17 
18         return s.substring(start,end);        
19     }
20 }

 

posted @ 2014-11-27 06:46  LiBlog  阅读(136)  评论(0编辑  收藏  举报