Given a stringS, find the longest palindromic substring inS. You may assume that the maximum length ofSis 1000, and there exists one unique longest palindromic substring.
java
题目描述:找出一个字符串中的最长回文子串。算法
本人思路:ide
相似于网上所写的中心扩展法。从字符串中的每一个位置开始向两边扩展,找到最长的回文。spa
时间复杂度:O(n²),leetcode经过时间:15ms。code
public class Solution {
public static String longestPalindrome(String s) {
char[] cs = s.toCharArray();
int begin=0,end=0;
int size = s.length();
int out = 0;//中心位置
for(int befor=out,after=out;out
{
//判断是否abcba类回文
for(;befor>0&&after
{
if(cs[befor-1] != cs[after+1])
break;
}
if(befor != after && after-befor>end-begin)
{
end=after;
begin=befor;
}
//判断是否abccba类回文
for(befor = out,after = out;befor>=0&&after
{
if(cs[befor] != cs[after+1])
break;
}
if(befor != after && after-(++befor)>end-begin)
{
end=after;
begin=befor;
}
//判断是否aaaaaa类回文
for(befor=out,after=out;after
{
if(cs[befor] != cs[after+1])
break;
}
if(after!=befor && after-befor>end-begin)
{
end=after;
begin=befor;
out = after;//跳太重复的序列
}
}
return s.substring(begin, end+1);
}
}
除了这种解法还有如下几种解法:leetcode
①暴力解决法:遍历字符串中的每一个子串,判断是否回文串,并更新最长回文串。字符串
②动态规划:思想为:若 [ i , j ] 为回文,则 [ i+1, j-1 ]也为回文。string
③Manacher's 算法。it
附上大神制做的PPT(很详细):http://faculty.utpa.edu/liuy2/algorithmSlides/Longest-Palindromic-Substring.pptxio