1.暴力O(n^3)
2.中心扩散O(n^2)
3.动态规划O(n^2),重要的是掌握思想,利用空间换时间,就是利用上一个状态求下一个状态
4.马拉车O(n):需要预处理+中心扩散,面试提思路就行,实际工作可能适用性不广
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { BufferedReader inputString = new BufferedReader(new InputStreamReader(System.in)); String str = inputString.readLine().trim(); System.out.println(longestPalindrome(str)); } public static String longestPalindrome(String s) { int len = s.length(); if (len < 2) { return s; } int maxLen = 1; int begin = 0; //dp[i][j]表示s[i...j]是否为回文串 // java 初始化boolean为false boolean[][] dp = new boolean[len][len]; char[] charArray = s.toCharArray(); //参考左下角填,一列列填 for (int j = 1; j < len; j++) { for (int i = 0; i < j; i++) { if (charArray[i] != charArray[j]) { dp[i][j] = false; } else { if (j - i < 3) { dp[i][j] = true; } else { dp[i][j] = dp[i + 1][j - 1]; } } if (dp[i][j] && j - i + 1 > maxLen) { maxLen = j - i + 1; begin = i; } } } return s.substring(begin, begin + maxLen); } }