您的位置:首页 > 其它

Longest Palindromic Substring

2015-07-15 21:10 316 查看
题目: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.

也就是求最长回文子字符串。回文就是指从左到右和从右到左是相同的字符串。如abba,aba。

public static String longestPalindrome(String s) {
if(s.isEmpty())
return null;
if(s.length()==1)
return s;
String longest=s.substring(0,1);
for(int i=0;i<s.length();i++){
// get longest palindrome with center of i
String temp=helper(s, i, i);
if(temp.length()>longest.length())
longest=temp;
// get longest palindrome with center of i,i+1
temp=helper(s, i, i+1);
if(temp.length()>longest.length())
longest=temp;
}
return longest;
}
// Given a center, either one letter or two letter, Find longest palindrome
public static String helper(String s,int start,int end){
while(start>=0&&end<s.length()&&s.charAt(start)==s.charAt(end)){
start--;
end++;
}
return s.substring(start+1,end);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: