题解 | #最长回文子串#
最长回文子串
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); String str = sc.nextLine(); int len = str.length(); int max = 0; for(int i=0;i<len;i++){ //回文串长度为奇数的情况 max = Math.max(countPalindrome(str,i,i),max); //回文串长度为偶数的情况 max = Math.max(countPalindrome(str,i,i+1),max); } System.out.println(max); } public static int countPalindrome(String str, int start,int end){ int count = 0; while(start>=0&&end<str.length()&&str.charAt(start)==str.charAt(end)){ if(start == end) //回文串长度为奇数,最中间为一个字符 count++; else count+=2; start--; end++; } return count; } }