题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
import java.util.*;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String s = in.next();
int length = s.length();
int maxLength = 0;
for (int i = 0; i < length; i++) {
for (int j = length; j > i; j--) {
//长度达标、首位相同,再判断是否为回文子串
if (j - i > maxLength && s.charAt(j - 1) == s.charAt(i)) {
String temp = s.substring(i, j);
//是回文子串
if (check(temp)) {
//更新结果
maxLength = temp.length();
}
}
}
}
System.out.println(maxLength);
}
}
public static boolean check(String s) {
StringBuilder sb = new StringBuilder(s);
return s.equals(sb.reverse().toString());
}
}
查看5道真题和解析