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.
题目来源:https://leetcode.com/problems/longest-palindromic-substring/
题意:给定某一字符串,找到最长的回文子串!(注意:最大回文子串是唯一,即一个字符串不能同时存在多个最长回文子串)
解法:从长度为len (len = s.length(), len = s.length() –)开始寻找该字符串的子串,一旦在某一len值找到符合要求子串str,则该str就是要找的最长回文子串,其他长度的回文子串则不需要考虑。
/**
* 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.
* @author ganyee
*
*/
public class LongestPalindromicSubstring {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(longestPalindrome("abaaba "));
}
public static String longestPalindrome(String s) {
String maxStr = "";
for(int i = s.length();i >= 0;i --){
maxStr = isPalindrom(s, i);
if(maxStr.length() !=0)
break;
}
return maxStr;
}
public static String isPalindrom(String s,int len){
int i = 0;
StringBuffer str = new StringBuffer(s);
String str1;
String str2;
String str3 = "";
while(i + len <= s.length()){
str1 = str.substring(i,i + len).toString();
StringBuffer str4 = new StringBuffer(str1);
str2 = str4.reverse().toString();
if(str1.equals(str2) && str3.length() < str1.length()){
str3 = str1;
break;
}
else{
i ++;
}
}
return str3;
}
}
另解:引自
1)http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-i.html
2)http://articles.leetcode.com/2011/11/longest-palindromic-substring-part-i.html