题解 | #最长回文子串#
可以使用动态规划和暴力寻找子串。
动态规划:注意双层循环的方向要是相反的,这样才是由短到长扩散开。
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); // dp[i][j]表示从i到j的字符是否为回文子串 int max = 0; boolean[][] dp = new boolean[str.length()][str.length()]; for (int i = 0; i < str.length(); i++) { dp[i][i] = true; max = 1; } for (int i = 0; i < str.length()-1; i++) { if (str.charAt(i) == str.charAt(i+1)) { dp[i][i+1] = true; max = 2; } } for (int i = str.length()-3; i >= 0; i--) { for (int j = i+2; j < str.length(); j++) { if (str.charAt(i) == str.charAt(j)) { dp[i][j] = dp[i+1][j-1]; if (dp[i][j]) { max = Math.max(max, j - i + 1); } } } } System.out.println(max); } }
暴力子串
import java.util.*; public class Main { public static void main(String args[]) { Scanner input = new Scanner(System.in); String s = input.nextLine(); int max = 0; /** *双指针遍历找到最长子串 */ for (int i = 0; i < s.length(); i++) { for (int j = s.length(); j > i; j--) { String toBeJuged = s.substring(i, j); if (isPalindromeString(toBeJuged)) { max = Math.max(max, j - i); } } } System.out.print(max); } /** *判断一个字符串是否是回文字符串的方法 */ static boolean isPalindromeString(String s) { return s.equals(new StringBuilder(s).reverse().toString()); } }