双重for循环。基于牛客692041258号的代码优化。
密码截取
https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1
import java.util.Scanner; public class Main { public static boolean isSymmetry(String str) { int n = str.length(); for (int i = 0; i < n / 2; i++) { if (str.charAt(i) != str.charAt(n - i - 1)) { return false; } } return true; } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNextLine()) { String str = in.nextLine(); int n = str.length(); int max_len = 1; for (int i = 0; i < n; i++) { for (int j = n - 1; j > i; j--) { if (isSymmetry(str.substring(i, j + 1))) { max_len = Math.max(j - i + 1, max_len); } } } System.out.println(max_len); } } }