leetcode--5. Longest Palindromic Substring

时间:2021-05-25 14:00:01

题目来自 https://leetcode.com/problems/longest-palindromic-substring/

题目: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,在S中找出最长回文子字符串。你可以设置字符串的最大长度为1000,这里面存着一个唯一的最长回文字符串。

方法1:

以中心对称的方法检测回文

public class LongestPalindromicSubstring {
public static String expendCenterStr(String s,int r,int l){
if (s.length()==0){
return "";
}
int n=s.length();
while (r>=0&&l<n&&s.charAt(r)==s.charAt(l)){
r--;
l++;
}
return s.substring(r+1,l);
} public static String longestPalindrome(String s) { String longestStr=s.substring(0,1);
for (int i=0;i<s.length();i++){
String s1=expendCenterStr(s,i,i);
if (s1.length()>longestStr.length()){
longestStr=s1;
}
String s2=expendCenterStr(s,i,i+1);
if (s2.length()>longestStr.length()){
longestStr=s2;
}
}
return longestStr;
} public static void main(String[] args) {
System.out.println(longestPalindrome("ffasfgcabbacgdsfs"));
}
}