题解 | #最长回文子串#
最长回文子串
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 的区别 String a = in.nextLine(); //使用双指针 int max=0; for(int i=0;i<a.length();i++){ for(int j=a.length();j>i;j--){ String s = a.substring(i,j); //是否回文是指 字符串和翻转后的字符串也是一样的 boolean isBack = s.equals(new StringBuffer(s).reverse().toString()); if(isBack){ max = Math.max(max,j-i); } } } System.out.print(max); } }
双指针法,双重循环遍历字符串,从两头开始分别遍历,去找一段字符串,通过 StringBuffer.reverse 方法翻转字符串后,与原字符串比对是一样的话,就满足回文字符串,这样记录长度,然后通过 Math.max 取最大值即可