题解 | 最长回文子串
最长回文子串
https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int result=0;
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String input=in.nextLine();
if(input!=null&&input.length()>0){
result=getLongestPalindrome(input).length();
System.out.println(result);
}
}
}
//中心扩展法获取回文子串的长度
private static int expandAroundCenter(String s,int left,int right){
while(left>=0&&right<s.length()&&s.charAt(left)==s.charAt(right)){
left--;
right++;
}
return right-left-1;
}
//中心扩展法获取最长的回文子串
public static String getLongestPalindrome(String str){
int start=0;
int end=0;
int len=0;
String result=null;
for(int i=0;i<str.length();i++){
//奇数回文子串
int m=expandAroundCenter(str,i,i);
//偶数回文子串
int n=expandAroundCenter(str,i,i+1);
len=Math.max(m,n);
if(len>end-start){
start=i-(len-1)/2;
end=i+len/2;
}
}
result=str.substring(start,end+1);
return result;
}
}
查看16道真题和解析