题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
import java.lang.Math;
import java.util.Scanner;
// 注意类名必须为 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
char[] str = in.nextLine().toCharArray();
int pdLength = Integer.MIN_VALUE;
for (int i = 0; i < str.length - 1; ++i) {
int l = 1;
if (str[i] == str[i + 1]) {
l = 2;
int left = i - 1, right = i + 2;
while (left >= 0 && right < str.length) {
if (str[left--] == str[right++]) {
l += 2;
} else break;
}
pdLength = Math.max(l, pdLength);
}
if (i > 0 && str[i - 1] == str[i + 1]) {
l = 3;
int left = i - 2, right = i + 2;
while (left >= 0 && right < str.length) {
if (str[left--] == str[right++]) {
l += 2;
} else break;
}
pdLength = Math.max(l, pdLength);
}
}
System.out.println(pdLength);
}
}
}

小天才公司福利 1171人发布