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.
题目描述:找出一个字符串中的最长回文子串。
本人思路:
类似于网上所写的中心扩展法。从字符串中的每个位置开始向两边扩展,找到最长的回文。
时间复杂度:O(n²),leetcode通过时间:15ms。
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<size;out++)
{
//判断是否abcba类回文
for(;befor>0&&after<size-1;befor--,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<size-1;befor--,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<size-1;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);
}
}
除了这种解法还有以下几种解法:
①暴力解决法:遍历字符串中的每个子串,判断是否回文串,并更新最长回文串。
②动态规划:思想为:若 [ i , j ] 为回文,则 [ i+1, j-1 ]也为回文。
③Manacher's 算法。
附上大神制作的PPT(很详细):http://faculty.utpa.edu/liuy2/algorithmSlides/Longest-Palindromic-Substring.pptx