题目叙述
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.
本体可以使用动态规划去解答,但是我用了之后没能AC,也可以使用从中间向两边延伸去查找最长回文子串。先提供第二种方式的解答,通过提交
public class Solution {
public String longestPalindrome(String s) {
int max = Integer.MIN_VALUE;//最长回文子串长度;
String result = "";
for(int i=0;i<s.length();i++){
//奇数中心展开
String temp1 = expandFromCenterToEdge(s, i, i);
if(max<temp1.length()){
max = temp1.length();
result = temp1;
}
//偶数展开
String temp2 = expandFromCenterToEdge(s, i, i+1);
if(max<temp2.length()){
max = temp2.length();
result = temp2;
}
}
return result;
}
//写一个中间向两边扩展程序
public String expandFromCenterToEdge(String str,int l,int r){
int left = l;
int right = r;
//while循环是为了找到最长的串;
while(left>=0&&right<=str.length()-1&&str.charAt(left)==str.charAt(right)){
left--;
right++;
//System.out.println(left+"---"+right);
}
return str.substring(left+1,right);
}
}