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.
用DP,d[i][j]表示字符串i到j是否为回文
public class Solution {
public String longestPalindrome(String s) {
int max = 0;
int len = s.length();
int maxL = 0;
int maxR = 0;
for(int i=0; i<len; i++){
int l=i;
int r=i+1;
while(l>=0 && r<len && s.charAt(l)==s.charAt(r)){
if(max < r-l+1){
max = r-l+1;
maxL = l;
maxR = r;
}
l--;
r++;
}
l = i;
r = i;
while(l>=0 && r<len && s.charAt(l)==s.charAt(r)){
if(max < r-l+1){
max = r-l+1;
maxL = l;
maxR = r;
}
l--;
r++;
}
}
return s.substring(maxL, maxR+1);
}
}
本文介绍了一种使用动态规划方法来寻找给定字符串中最长回文子串的有效算法。通过两个循环遍历字符串,该算法能高效地找到唯一的最长回文子串。
604

被折叠的 条评论
为什么被折叠?



