题解 | #最长回文子串#
最长回文子串
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.hasNextLine()) { // 注意 while 处理多个 case
String str = in.nextLine();
//尋找所有重疊的坐標
List<int[]> coordinate = new ArrayList<>();
for (int i = 0, k = 1 ; k < str.length(); k++, i++) {
if (str.charAt(i) == str.charAt(k)) {
int a [] = {i, k};
coordinate.add(a);
}
}
//雙重循環尋找最大值
int max = 0;
int result = 0;
for (int[] cor : coordinate) {
for (int x = cor[0], y = cor[1]; x >= 0 && y <= str.length() - 1; x--, y++) {
if (str.charAt(x) == str.charAt(y)) {
max = y - x + 1;
}else{
break;
}
}
result = Math.max(result, max);
max = 0;
}
int singleton = 0;
for (int i = 0; i < str.length(); i++) {
for (int k = i - 1, z = i + 1; k >= 0 && z < str.length(); k--, z++) {
if (str.charAt(k) == str.charAt(z)) {
singleton = z - k + 1;
}
if (str.charAt(k) != str.charAt(z)) {
result = Math.max(result, singleton);
singleton = 0;
break;
}
}
}
System.out.print(result);
}
}
}
