题解 | #最长回文子串#
最长回文子串
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); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String str = in.nextLine(); int sum = 0; int[][] dp = new int[str.length()][str.length() / 2 + 1]; int[][] dd = new int[str.length()][str.length() / 2 + 1]; for (int i = 0; i < str.length(); i++) { dp[i][0] = 0; } for (int i = 0; i < str.length(); i++) { dd[i][0] = 1; } for (int i = 1; i < str.length() - 1; i++) { for (int j = 1; j < str.length() / 2+1; j++) { if (i - j + 1 >= 0 && i + j < str.length() && str.charAt(i - j + 1) == str.charAt(i + j)) { dp[i][j] = dp[i][j - 1] + 2; sum = Math.max(dp[i][j], sum); } else break; } } for (int i = 1; i < str.length() - 1; i++) { for (int j = 1; j < str.length() / 2+1; j++) { if (i - j >= 0 && i + j < str.length() && str.charAt(i - j) == str.charAt(i + j)) { dd[i][j] = dd[i][j - 1] + 2; sum = Math.max(dd[i][j], sum); } else break; } } System.out.println(sum); } } }