题解 | #最长回文子串#
杨辉三角的变形
http://www.nowcoder.com/practice/8ef655edf42d4e08b44be4d777edbf43
给定一个仅包含小写字母的字符串,求它的最长回文子串的长度。
所谓回文串,指左右对称的字符串。
import java.util.Scanner; public class Main{ public static void main(String[] args){ //ccabbadc cdabbacc abcbaaa aaabcba Scanner sc = new Scanner(System.in); while(sc.hasNext()){ String str = sc.nextLine(); int max=0; for(int i=0;i<str.length();i++){ for(int j=i+2;j<=str.length();j++){ String sub = str.substring(i,j); int subLen= sub.length(); if(subLen>=2){ String temp = sub.substring(0,subLen/2); StringBuilder temp2= new StringBuilder(sub.substring(subLen%2==0? (subLen/2) : (subLen/2+1))); temp2.reverse(); if(temp.equals(temp2.toString())){ max=max>sub.length()?max:sub.length(); } } } } System.out.println(max); } } }