5. Longest Palindromic Substring

来源:互联网 发布:推荐系统算法 编辑:程序博客网 时间:2024/04/30 12:01

一,题目

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,j == i       true
 2,j+1 == i   s[j] == s[i] 
 3,否则
     s[j+1][i-1] && s[j]==s[i]

三,代码如下

public  String longestPalindrome(String s) {

if(s ==null || s.length() == 1){

returns;

}

char[] chs = s.toCharArray();

int len = s.length();

int max = 0;

int start = 0,end = 0;

boolean[][]memo = new boolean[len][len];

/*

*1,j == i       true

*2,j+1 == i   s[j] == s[i] 

*3,否则

*     s[j+1][i-1] && s[j]==s[i]

*/

for(inti=0; i<len;i++){

for(intj=0; j<=i;j++){

if(j ==i){

memo[j][i] =true;

}else if((j+1) == i){

memo[j][i] = (chs[j] ==chs[i]);

}else {

memo[j][i] = (memo[j+1][i-1] && (chs[j] ==chs[i]));

}

if(!memo[j][i]){

continue;

}

if(i-j +1 >max){

max = i-j+1;

start = j;

end = i;

}

}

}

return s.substring(start, end+1);

}


0 0
原创粉丝点击