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.
给定字符串S,找到该字符串中最长的回文子串。假设这个子串的最大长度为1000,并且这个最长回文子串是存在且唯一的。
回文字符串是以中心轴对称的,所以如果我们从下标 i 出发,用2个指针向 i 的两边扩展判断是否相等
注意 回文字符串有奇偶对称之分
public String longestPalindrome(String s)
{
if(s==null||s.length()<=1)
return s;
String maxres="";
String res="";
for(int i=0;i<s.length();i++)
{
res=getnum(s,i,i);//回文串以i为中心
if(maxres.length()<res.length())
maxres=res;
res=getnum(s,i,i+1);//回文串以i,i+1为中心
if(maxres.length()<res.length())
maxres=res;
}
return maxres;
}
private static String getnum(String s, int begin,int end)
{
while(begin>=0&&end<=s.length()-1)
{
if(s.charAt(begin)==s.charAt(end))
{
begin--;
end++;
}
else
break;
}
return s.substring(begin+1,end);
}版权声明:本文为博主原创文章,转载注明出处
[LeetCode][Java]Longest Palindromic Substring
原文:http://blog.csdn.net/evan123mg/article/details/46771155