题解 | 最长回文子串
最长回文子串
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); String str = in.nextLine(); int maxLength = 0; for (int i = 0; i < str.length(); i++) { for (int j = i + 1; j <= str.length() / 2; j++) { if (j - i < (double)maxLength / 2) { continue; } String left = str.substring(i, j); String right = str.substring(j, j + (j - i)); StringBuilder sb = new StringBuilder(right).reverse(); if (left.equals(sb.toString())) { maxLength = (j - i) * 2; } else { if (j - 1 > i) { right = str.substring(j - 1, j - 1 + (j - i)); sb = new StringBuilder(right).reverse(); if (left.equals(sb.toString())) { maxLength = (j - i - 1) * 2 + 1; } } } } } System.out.println(maxLength); } }