码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-Longest Palindromic Substring

时间:2014-11-27 07:59:55      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

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 }

 

Leetcode-Longest Palindromic Substring

标签:style   blog   io   ar   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/lishiblog/p/4125533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!