题解 | #最长回文子串#
最长回文子串
https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); while (sc.hasNext()) { String str = sc.nextLine(); int maxLength = 0;// 最长回文子串的长度 String child = "";// 子串 String[] split = str.split(""); for (int i = 0; i < split.length; i++) { for (int j = i+1; j <= split.length; j++) { // 遍历所有子串 child = str.substring(i, j); // 子串是回文子串,且比现有回文子串长度大,则更新最大值 if(checkChild(child) && maxLength < child.length()){ maxLength = child.length(); } } } System.out.println(maxLength); } } // 校验字符串是否是回文子串 public static boolean checkChild(String child) { for(int k = 0;k<child.length()/2;k++){ // 判断是否对称 if(!(child.charAt(k) == child.charAt(child.length()-1-k))){ return false; } } return true; } }